-1

Am making an XMLHttprequest fromjavascript to my node server.

this is my request:

        var data = { "fname": "Fasal", "lname": "Rahman" };
        var body = JSON.stringify(data);
        var xhttp = new XMLHttpRequest();
        xhttp.open("POST", "/admin");
        xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhttp.send(body);

this is my post rout:

app.post("/admin", function(req, res) {
   console.log(req.body);
});

I am using body-parser

const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));

the body i am getting from the request from the server is like this

{ '{"fname":"Fasal","lname":"Rahman"}': '' }

the entire body json as the key and value as ''

i need the body to be in key value pair like this {fname:"Fasal",lname:"Rahman"}

which is the correct way of sending JSON object?

1 Answers1

0

Your Content-type header should be "application/json":

const data = { "fname": "Fasal", "lname": "Rahman" };
const xhttp = new XMLHttpRequest();
xhttp.open("POST", "/admin");
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send(JSON.stringify(data));
jarmod
  • 71,565
  • 16
  • 115
  • 122