Search code examples
javascriptjsonrestfetch-api

Why is my fetch() sending an empty JSON body?


I've been trying to send a JSON data using fetch but the backend receives an empty object. In my Client JS I have

const user = "company1";
const username = "muneeb";

const data = {user, username};

fetch("http://127.0.0.1:3000/users/api/login", {
    method: 'POST',
    body: JSON.stringify(data)
}).then((response) => {
    console.log(response);
});

The server side has:

router.post('/users/api/login', async (req, res, next) => {

    try {
        // console.log(request.body);
        const request = JSON.stringify(req.body);

        let imageTitles = [];
        console.log(request);

        *its random from here on out but you get the idea*

        await components.getImages(imageTitles);
        const finalKey = imageTitles.join("");
        let images = await components.output(req.body.user ,req.body.username);
        res.send(components.jsonConverter(imageTitles, images)); //---Top priority
        db.setPassword(req.body.user, req.body.username , finalKey);
    } catch (err) {
        console.log(err);
        res.send(err).sendStatus(500);
    };
})

A few things I have already tried :

It works perfectly in Insomnia(postman).

express.json() is present , it helped me go from undefined to blank JSON.

I have enabled cors settings.

That's it for now.


Solution

  • The body parser express.json will only be applied for requests with Content-Type: application/json. You have to add the content type to your fetch call:

    fetch("http://127.0.0.1:3000/users/api/login", {
      method: 'POST',
      body: JSON.stringify(data),
      headers: {
        'Content-Type': 'application/json'
      }
    })