/ 发送 POST 请求
pm.sendRequest({
url: 'https://api.example.com/users',
method: 'POST',
header: {
'Content-Type': 'application/json',
// 可选:添加其他请求头
},
body: {
mode: 'raw',
raw: JSON.stringify({
name: 'John Doe',
email: 'john.doe@example.com'
})
}
}, function (err, res) {
if (err) {
console.error(err);
return;
}
console.log('响应数据:', res.json());
// 可在这里处理响应数据并保存到环境变量或进行其他操作
});
上面的代码中,我们使用 pm.sendRequest()
方法发送了一个 POST 请求至 https://api.example.com/users
,并在请求的主体(body)中发送了一个 JSON 对象。可以根据实际情况修改 url
、header
和请求主体等内容。在回调函数中,同样可以处理来自服务器的响应数据,并进行进一步的操作。
将上述代码添加到 脚本中,并确保在请求发送前保存脚本以便后续运行。点击运行按钮后,脚本将发送 POST 请求,并在控制台中输出响应数据。
在 JavaScript 中,对象的 key 通常是一个字符串,因此在构建 JSON 数据时,key 是需要用引号括起来的。而对于 key 的值(即属性值),如果是字符串类型,也需要用引号括起来。
在上面示例代码中的 JSON.stringify 中,name
和 email
并不需要加上引号,因为它们是作为 key(属性名)出现的,并不是作为字符串值。JavaScript 在处理对象字面量时,key 可以是不带引号的字符串。
实际上,以下两种写法在 JavaScript 中都是合法的:
{
"name": "John Doe",
"email": "john.doe@example.com"
}
// 或者
{
name: "John Doe",
email: "john.doe@example.com"
}
所以在发送 POST 请求时,在构建 JSON 对象时 key 部分不需要加上引号,只需要确保 key 和 value 都是符合 JSON 规范的。JavaScript 引擎会根据上下文正确地解析对象的 key 和 value。
总结:
// Example with a plain string URL
pm.sendRequest('https://postman-echo.com/get', (error, response) => {
if (error) {
console.log(error);
} else {
console.log(response);
}
});
// Example with a full-fledged request
const postRequest = {
url: 'https://postman-echo.com/post',
method: 'POST',
header: {
'Content-Type': 'application/json',
'X-Foo': 'bar'
},
body: {
mode: 'raw',
raw: JSON.stringify({ key: 'this is json' })
}
};
pm.sendRequest(postRequest, (error, response) => {
console.log(error ? error : response.json());
});
// Example containing a test
pm.sendRequest('https://postman-echo.com/get', (error, response) => {
if (error) {
console.log(error);
}
pm.test('response should be okay to process', () => {
pm.expect(error).to.equal(null);
pm.expect(response).to.have.property('code', 200);
pm.expect(response).to.have.property('status', 'OK');
});
});
你可以使用该方法从预请求或测试pm.sendRequest
脚本异步发送请求。如果你同时执行计算或发送多个请求,而无需等待每个请求完成,这允许你在后台执行逻辑。你可以通过添加回调函数来避免阻塞问题,以便你的代码可以在 Postman 收到响应时做出响应。然后,你可以对响应数据执行所需的任何其他处理。
你可以向该pm.sendRequest
方法传递一个 URL 字符串,或者可以提供一个完整的 JSON 格式的请求配置,包括 header、方法、正文 等 。