1

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

wololoo
  • 147
  • 1
  • 1
  • 9
  • You most likely need to set the [header](https://stackoverflow.com/questions/29775797/fetch-post-json-data): `Content-Type: application/json` so express properly parses the body. –  Sep 16 '20 at 16:25
  • @ChrisG I tried that too! Then I get a `HTTP/1.1 400 Bad Request` error in the browser console. – wololoo Sep 16 '20 at 16:33
  • Did you set up a JSON parser in your express code? `app.use(express.json())` before your routes. –  Sep 16 '20 at 16:38
  • Yes, let me add more of my server code. Feels like the issue is on client-side as my server code is working correctly when I post a form. – wololoo Sep 16 '20 at 16:57
  • @ChrisG I tried setting headers in the first method, but not with `fetch`. Now I tried as [this answer](https://stackoverflow.com/a/42493030/14051057) and it works. I marked my question as a duplicate. Thank you very much for your help! – wololoo Sep 16 '20 at 17:11

0 Answers0