I have been searching for an hour and I could not found a client-side code that works.
I'm trying to send an object to my Node.js backend, process the object in the server and show the result on the same page, without changing the page URL.
My object has nested objects and arrays inside, so I'm not sure if I can serialize it and use a GET request instead.
My backend code:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json({limit:'50mb'}));
app.use(bodyParser.urlencoded({extended:false,limit:'50mb'}));
app.post('/server', function(req,res,next){
console.log(JSON.stringify(req.body));
res.send("foo");
});
app.listen(8900,function(){});
It works when I post a form, but that changes the page URL, so I'm looking a plain JavaScript alternative to $.ajax()
.
Here is what I tried so far:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if(this.readyState==4 && this.status==200) {
console.log(this.responseText);
}
};
xhttp.open("POST", "/server", true);
xhttp.send(data);
Did not work.. I also tried this
fetch("/server", {
method : "POST",
body: data
}).then(
response => response.text()
).then(
html => console.log(html)
);
I also tried to send JSON.stringify(data)
. In all cases, my server logs an empty req.body
.
This answer from another thread does work in the server side, but since it does form.submit()
it changes the page URL.
How can I do this without reloading the page?
I know that I can use jQuery or socket.io for these purposes but I prefer a plain JavaScript solution if possible.
Thanks