postman使用教程12-预处理(pre-request) 发送请求
前言
可以使用 pm.sendRequest 方法从“pre-request”或“Tests”脚本异步发送请求。
如果您要执行计算或同时发送多个请求,而不必等待每个请求完成,则可以在后台执行逻辑。
pre-request 发送请求
点 Send a request 快速生成一个请求示例
- pm.sendRequest 是发送一个请求
- function中的err表示请求返回的错误信息,
- response表示响应内容
- console.log()是控制台输出日志
pm.sendRequest("https://postman-echo.com/get", function (err, response) {
console.log(response.json());
});
发送一个post请求示例
// 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());
});
参数说明:
- const是js中用来定义变量的关键字,由const定义的变量不可以修改,而且必须初始化
- url表示要发送的请求url地址;
- method指定请求方法 GET/POST;
- header定制请求头信息,传json格式的数据的话,需定义请求头为Content-Type:application/json
- body 表示post请求body参数
- JSON.stringify() 方法是将一个JavaScript值(对象或者数组)转换为一个JSON字符串
更多示例
以下是官方文档给的示例https://learning.postman.com/docs/writing-scripts/script-references/postman-sandbox-api-reference/
// 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');
});
});
请求定义和响应结构参考文档
Request 请求参数参考文档[http://www.postmanlabs.com/postman-collection/Request.html#~definition]
Response 返回参考文档http://www.postmanlabs.com/postman-collection/Response.html
作者-上海悠悠 blog地址 https://www.cnblogs.com/yoyoketang/
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2019-05-10 appium+python自动化63-使用Uiautomator2报错问题解决
2018-05-10 appium+python自动化44-appium命令行模式
2018-05-10 python接口自动化21-下载excel文件(Content-Type:octets/stream)
2017-05-10 python接口自动化2-发送post请求