Search code examples
javascriptnode.jsfetchweb-deployment

node server cannot find the data in the body


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.


Solution

  • 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 : {
       ...
    }
    ...