Thursday 8 June 2017

fetch() header shows as application/x-www-form-urlencoded instead of application/json

I'm running a React app on heroku using a node.js backend via Express. In the frontend, I want to send a POST request containing a JSON payload, which is sent like this:

fetch('/api/shows', {
        method: 'POST',
        accept: 'application/json',
        headers: new Headers({
            'Content-Type': 'application/json',
        }),
        // mode: 'cors',    // tried this, but no effect
        // cache: 'default',    // tried this, but no effect
        body: JSON.stringify({ "foo": "bar" }),
    }).then(response => {
        return response.json();
    }).then(response => {
        // … handling the response …
    }).catch(err => {
        // … handling errors …
    });

The backend is set up like this:

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

const app = express();

app.set('port', (process.env.PORT || 3001));

if (process.env.NODE_ENV === 'production') {
    app.use(express.static('frontend/build'));
}

app.post('/api/shows', bodyParser.json(), (req, res) => {
    const data = req.body;
    console.log(data); // shows {}
});

Locally this all works fine, but deployed on heroku the request comes in with content type application/x-www-form-urlencoded instead of application/json, which is why the body-parser middleware doesn't parse the JSON.

Oddly enough this did work a couple days ago when I tried it once and I'm not aware of any changes I made in this area in the meantime.

What is causing the header to be wrong despite being explicitly set for the request? I could configure the middleware to read it anyway, but this seems like a workaround. I'd like to understand the actual root cause of the problem instead.



via Ingo Bürk

No comments:

Post a Comment