如何在poster中的Pre-request Script部分运行GraphQL请求



我想在实际请求运行之前运行一个查询,从预请求响应中获取一个值,并将其设置在集合变量中。我在测试RESTAPI时遇到了运行以下内容的问题。

这就是我尝试做的

const getUserBeforeUpdate = {
url: pm.environment.get("base-url"),
method: 'POST',
header: {
'content-type': 'application/json',
'Authorization': `Bearer ${pm.environment.get("token")}`},
body: JSON.stringify({query: '{ user { profile {id} } }'})
};

pm.sendRequest(getUserBeforeUpdate, function(err, response) {
pm.expect(response.code).to.eql(200);

// set collection variable from the response
});

但我收到一个控制台错误,说明

There was an error in evaluating the Pre-request Script:  Error: Unexpected token u in JSON at position 0

在graphql中链接请求的正确方法是什么?

集合变量可通过collectionVariables访问。这应该对你有用:
const getUserBeforeUpdate = {
url: pm.collectionVariables.get("base-url"),
method: 'POST',
header: {
'content-type': 'application/json',
'Authorization': `Bearer ${pm.collectionVariables.get("token")}`},
body: JSON.stringify({query: '{ user { profile {id} } }'})
};

pm.sendRequest(getUserBeforeUpdate, function(err, response) {
pm.expect(response.code).to.eql(200);

// set collection variable from the response
});

我没有能力运行您的请求,但这能工作吗?

const getUserBeforeUpdate = {
url: `${pm.environment.get("base-url")}`,
method: 'POST',
header: {
'content-type': 'application/json',
'Authorization': `Bearer ${pm.environment.get("token")}`},
body: JSON.stringify({
query: 'query { user { profile { id } } }'
})
};

pm.sendRequest(getUserBeforeUpdate, function(err, response) {
pm.expect(response.code).to.eql(200);
// set collection variable from the response
});

我可以通过将url值直接作为字符串更改为实际url来解决这个问题。我不知道为什么从环境中获取变量还不起作用。

最新更新