node server cannot find the data in the body

113 views Asked by At

i am sending a post request from fetch but the nodejs server is not able to access the body from the post request. I tried req.body but it just returns empty brackets.

const express = require('express');
const bodyParser=require("body-parser");


const app = express();
app.use(bodyParser.urlencoded({ extended: true}))
app.use(bodyParser.json());
app.use(express.json());

app.get("/user",function(req,res){
    
    res.send("just Checking");
    
});




app.post("/user", (req, res) => {
    console.log(req.body);
    res.send("got the data");

});
    




app.listen(3000,function(res){

    console.log("server is workig a t local host 3000");

    
    });
    

This is the browser side code



const checking = { name:"badmintion" }
function yo (){ 
     fetch("/user",{
method : "POST",
Headers : {
'Content-Type':'application/json'

},
body: JSON.stringify(checking)
})
}


yo();

In the browser i can see that the data is being sent but i am unable to recieve the in the nodejs server it just shows empty brackets.

3

There are 3 answers

0
Stanley Ulili On BEST ANSWER

Edit: I was able to recreate the server code locally on my machine. I didn't find any issues. I used Postman to send the JSON to the /user route. The issue you might be having is in the front end.

Headers should be lowercase. You have capitalized it:

...
     fetch("/user",{
method : "POST",
headers : {
   ...
}
...
0
netlorecomment On

To avoid any conflict for (parse json) better that remove body parser completely and try again.

For request, according to stanley, headers set as lowercase. Its will be work.

This tutorial maybe help u:

https://www.geeksforgeeks.org/express-js-express-json-function/amp/

0
jkalandarov On

Make sure you're sending data in a JSON format so that express can parse it into object: enter image description here