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/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM