I am developing a website (client + server) that runs from the same machine. I haven't found any errors in chrome's developer tools, so I don't know where the problem is.
I try to POST a string from the client to the Node back-end, but upon performing
url.parse(request.url, true).query
the result is empty.
Here is my client:
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "http://localhost:8080/newComment", true);
xhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhttp.send("val=" + commentString);
My commentString is "hey there"
Here is my server:
var path = url.parse(request.url).pathname;
else if (path == "/newComment") {
console.log("query: " + url.parse(request.url, true).body);
//setNewComment(comment);
response.writeHead(200, {
'Content-Type': 'text/plain',
'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Methods': 'GET,PUT,POST,DELETE'
}); // enable cors
response.write("Recieved request");
response.end();
}
And I am at the website
file:///C:/Users/.../website.html?name=hey+there
So I'd like my Node server to print out "query: hey there" but instead it prints "query undefined"
You are trying to access the body, and this is right, yet the url doesn't hold the body's content, you should either accumulate it by listening to 'data' events:
let body = [];
request.on('data', (chunk) => {
body.push(chunk);
}).on('end', () => {
body = Buffer.concat(body).toString();
// at this point, `body` has the entire request body stored in it as a string
});
or use "express" and "body-parser".
1.Go to the request body section: https://nodejs.org/en/docs/guides/anatomy-of-an-http-transaction/
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments