1

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

1 Answers1

0

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.

Barmar
  • 596,455
  • 48
  • 393
  • 495
  • Can you do this when you use ```app.use(express.urlencoded({extended:true}))```? – vitusverden Oct 09 '19 at 16:31
  • I don't know, I'm not a node.js programmer. But I suspect not, that expects the parameters to be `username=XXX&password=YYY` – Barmar Oct 09 '19 at 16:33