首页 > 解决方案 > 记录 XHR 的请求负载

问题描述

每当发出 XHR 请求有效负载时,我想在 Chrome 的控制台中打印有效负载,我将如何执行此操作?任何和所有的想法都非常受欢迎。

标签: javascriptxmlhttprequest

解决方案


也许我还没有理解你的问题,打印变量到控制台你需要下一个代码

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);

推荐阅读