Postman(Pre-request Script)构建请求之前的操作
Postman(Pre-request Script)构建请求之前的操作
一、发送GET请求
有时候我们需要在请求之前进行某些操作,比如登录并获取token,然后才能正常执行查询操作,否则会报授权问题。所以我们可以在Pre-request Script中编写我们需要进行的前置操作。如图:
get请求的参考代码如下:
// 获取当根路由地址
var host_url = pm.environment.get("url");
// 构建get请求
const getRequest = {
url: host_url+"/sys/get",
method: 'GET'
};
//发送请求
pm.sendRequest(getRequest, (err, response) => {
if (err) {
console.log(err);
} else {
//设置环境变量
pm.environment.set("accessToken", response.json()['accessToken']);
console.log(response.json()['accessToken'])
}
});
二、发送POST请求
1、content-type
为json
格式
// 获取当根路由地址
var host_url = pm.environment.get("url");
// 登录用户名及密码
var data = {
"userId": "XXX",
"password": "XXX"
}
// 构建请求
const postRequest = {
url: host_url+"/sys/login",
method: 'POST',
header:'Content-Type:application/json',
body:{
mode: 'raw',
raw: JSON.stringify(data)
}};
//发送请求
pm.sendRequest(postRequest, function (err, response) {
console.log(response.json());
//设置环境变量
pm.environment.set("accessToken", response.json()['accessToken']);
});
2、content-type
为x-www-form-urlencoded
格式
// 获取当根路由地址
var host_url = pm.environment.get("url");
// 登录用户名及密码
var data = {
"userId": "XXX",
"password": "XXX"
}
// 构建请求
const postRequest = {
url: host_url+"/sys/login",
method: 'POST',
header:'Content-Type:application/x-www-form-urlencoded',
body: {
mode: 'x-www-form-urlencoded',
raw: "organCode=10000062"
}};
//发送请求
pm.sendRequest(postRequest, (err, response) => {
if (err) {
console.log(err);
} else {
console.log(response.json());
}
});
或者
// 获取当根路由地址
var host_url = pm.environment.get("url");
// 登录用户名及密码
var data = {
"userId": "XXX",
"password": "XXX"
}
// 构建请求
const postRequest = {
url: host_url+"/sys/login",
method: 'POST',
header:'Content-Type:application/x-www-form-urlencoded',
body: {
mode: 'urlencoded',
urlencoded: "organCode=10000062"
}};
pm.sendRequest(postRequest, (err, response) => {
if (err) {
console.log(err);
} else {
console.log(response.json());
}
});
三、参考
https://learning.postman.com/docs/writing-scripts/pre-request-scripts/