How to send request in Postman script

Postman's Collection (collection)/Folder (subfolder of the collection)/Request (request) has two script areas, Pre-request script and Tests, which can use scripts before and after sending the request respectively (based on Javascript to implement various operate)

When encountering a dependent interface, such as logging in or obtaining parameters from the results of the previous interface, we often need to send the dependent request before the request. We can use pm in the Pre-request script. sendRequest implementation

 1. Send a GET request

Copyconst url = 'http://115.28.108.130:5000/api/user/getToken/?appid=136425';
// 发送get请求
pm.sendRequest(url, function (err, res) {
  console.log(err ? err : res.text());  // 控制台打印请求文本
});
 

You can cooperate with pm.environment.set(key:value) to save the data in the response to the environment variable for use in this request.
Example: Use the pre-request script to get the token and use it,

2. Send form format Post request

Copy//构造一个登录请求
const loginRequest = {
    url: 'http://115.28.108.130:5000/api/user/login/',
    method: "POST",
    body: {
        mode: 'urlencoded',  // 模式为表单url编码模式
        urlencoded: 'name=张三&password=123456'
    }
};
 
// 发送请求
pm.sendRequest(loginRequest, function (err, res) {
    console.log(err ? err : res.text());
});
 

 

The output information can be viewed by clicking the Postman menu bar ->view->Show Postman Console to open the console (open the console first, and then send the request)

3. Send request in JSON format

Copy// 构造一个注册请求
const regRequest = {
  url: 'http://115.28.108.130:5000/api/user/reg/',
  method: 'POST',
  header: 'Content-Type: application/json',  //注意要在Header中声明内容使用的类型
  body: {
    mode: 'raw',  // 使用raw(原始)格式
    raw: JSON.stringify({ name: '小小', password: '123456' }) //要将JSON对象转为文本发送
  }
};
 
//发送请求
pm.sendRequest(regRequest, function (err, res) {
  console.log(err ? err : res.json());  // 响应为JSON格式可以使用res.json()获取到JSON对象
});

 

4. Send XML format request
Sending XML format is similar to sending JSON format, just specify the content format and send the corresponding content

Copy//构造请求
const demoRequest = {
  url: 'http://httpbin.org/post',
  method: 'POST',
  header: 'Content-Type: application/xml',  // 请求头种指定内容格式
  body: {
    mode: 'raw',
    raw: '<xml>hello</xml>'  // 按文本格式发送xml
  }
};
 
//发送请求
pm.sendRequest(demoRequest, function (err, res) {
  console.log(err ? err : res.json());
});

 

Guess you like

Origin blog.csdn.net/kk_lzvvkpj/article/details/131730465