记录XHR的请求有效负载

时间:2018-09-30 10:52:39

标签: javascript xmlhttprequest

每当作出XHR请求有效负载时,我都想在Chrome的控制台中打印有效负载,我该怎么做?任何想法都非常受欢迎。

1 个答案:

答案 0 :(得分:1)

也许我不明白您的问题,要打印变量以控制台您需要下一个代码

  const method = 'POST';
  const requestUrl = '/';
  // Payload as a JSON object
  const payload = {name: 'test'};
  // Form the http request as a JSON type
  const xhr = new XMLHttpRequest();
  xhr.open(method, requestUrl, true);
  xhr.setRequestHeader('Content-Type', 'application/json');

  // When the request comes back, handle the response
  xhr.onreadystatechange = () => {
    if (xhr.readyState === XMLHttpRequest.DONE) {
      const statusCode = xhr.status;
      const responseReturned = xhr.responseText;
      // Print the response to the chrome console
      console.log(responseReturned);    
    }
  };

  // Send the payload as JSON
  const payloadString = JSON.stringify(payload);
  // Print the payloadString to chrome console
  console.log(payloadString);
  xhr.send(payloadString);
};