在 Linux 下使用 Postman 写脚本,通常指的是在 Postman 的 Pre-request Script(请求前脚本) 或 Tests(测试脚本) 中写 JavaScript 代码,而不是在 Linux shell 里写。下面分几种常见情况说明。
Postman 的脚本语言是 JavaScript(基于 Node.js 环境)。
常用于:
示例:
// 设置环境变量
pm.environment.set("timestamp", Date.now());
// 生成随机字符串
const random = Math.random().toString(36).substring(2);
pm.variables.set("randomStr", random);
常用于:
示例:
// 状态码断言
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});
// 提取返回值
const jsonData = pm.response.json();
pm.environment.set("token", jsonData.token);
Postman 本身有 GUI,但在 Linux 服务器常用 Newman 跑脚本。
npm install -g newman
Postman → Collection → Export → collection.json
newman run collection.json \
--environment env.json \
--reporters cli,html \
--reporter-html-export report.html
✅ 脚本逻辑仍然写在 Postman 的 Pre-request / Tests 里
如果你说的是“用 Linux 脚本调接口”,那一般用 curl:
curl -X POST http://localhost:8080/login \
-H "Content-Type: application/json" \
-d '{"username":"admin","password":"123456"}'
pm.request.headers.add({
key: "X-Timestamp",
value: Date.now().toString()
});
const crypto = require('crypto');
const sign = crypto
.createHmac('sha256', 'secret')
.update('data')
.digest('hex');
pm.environment.set("sign", sign);
| 场景 | 写法 |
|---|---|
| Postman GUI | JavaScript(Pre-request / Tests) |
| Linux 服务器 | Newman 跑 Collection |
| Shell 调用 | curl |
如果你能具体说一下:
我可以给你更精确的脚本示例。