Ad

How To Read Post Request Payload With Node.js And Express?

Ok, so my js sends a XMLHTTPRequest post every 3 seconds, with username and password as payload. My question is, how do i read this payload, when it is not submitted via a form, but js?

Client-side js

setInterval(() => {
    var xhr = new XMLHttpRequest();
    xhr.open('POST', "../getchat", true)
    xhr.onreadystatechange = (e) => {
        if (xhr.readyState == 4 && xhr.status == 200) {
            var response = JSON.parse(xhr.responseText);
            document.getElementById("chat").innerHTML = ""
            for (let i = 0; i < response.length; i++) {
                const element = response[i];
                document.getElementById("chat").innerHTML += "<p>" + element + "</p>"
            }
        }
    }
    xhr.setRequestHeader("Content-Type", "application/json")
    xhr.send({username: "#{username}", password: "#{password}"})

    }, 3000);```
Ad

Answer

You need to call JSON.stringify() to turn the object into JSON.

xhr.send(JSON.stringify({username: "#{username}", password: "#{password}"}));

Then see How do I consume the JSON POST data in an Express application for how to parse the JSON in the node.js code.

Ad
source: stackoverflow.com
Ad