Home > Enterprise >  JSON String not getting to the server (should be easy to solve if you know express js)
JSON String not getting to the server (should be easy to solve if you know express js)

Time:04-22

I am using express js but for some reason, the server is logging an empty object {} instead of the actual JSON string that I sent. I have worked with so many other technologies like flask, this makes no sense.

Code:

function upload () {
    fetch("http://localhost:8080/chat", {
        method: "POST",
        body: JSON.stringify({
            name: "Deska",
            email: "[email protected]",
            phone: "342234553"
        })
    }).then(result => {
        // do something with the result
        console.log("Completed with result:", result);
    }).catch(err => {
        // if any error occured, then catch it here
        console.error(err);
    });
}

app.post('/chat', function(req, res) {

let test = req.body;
console.log(test);
}

On the "upload" function I do not get the anything logged, and in the server, I get the an empty object {} I mentioned.

If you are to know my issue, I would appreciate help.

Thank you.

UPDATE:

Issue should be in the prontend, as sending the post request with postman works.

CodePudding user response:

I think the error could be happening because you are missing the Content-Type header. You could try this:

function upload () {
    fetch("http://localhost:8080/chat", {
        headers: {
            'Content-Type': 'application/json',
        }, 
        method: "POST",
        body: JSON.stringify({
            name: "Deska",
            email: "[email protected]",
            phone: "342234553"
        })
    }).then(result => {
        // do something with the result
        console.log("Completed with result:", result);
    }).catch(err => {
        // if any error occured, then catch it here
        console.error(err);
    });
}

You should also make sure that in your server you are using the express.json middleware, this way:

app.use(express.json());
  • Related