Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

167
Views
JSON String not getting to the server (should be easy to solve if you know express js)

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: "deska@gmail.com",
            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.

8 months ago · Santiago Trujillo
1 answers
Answer question

0

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: "deska@gmail.com",
            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());
8 months ago · Santiago Trujillo Report
Answer question
Find remote jobs