no nein
no nein

Reputation: 711

log the request payload of XHR

Whenever an XHR request payload is made, I want to print the payload in the console in Chrome how would I go about doing this? Any and all ideas are very welcome.

Upvotes: 0

Views: 2372

Answers (1)

Sanchonn
Sanchonn

Reputation: 169

Maybe I haven't understood your questions, to print the variable to console you need next code

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

Upvotes: 0

Related Questions