Search code examples
node.jsreactjsexpressserveraxios

POST request from React to Express


So I'm having an issue making a post request from React to my Express server backend: the request payload is correctly structured as far as I can tell, and I'm able to send back a hardcoded response from server and receive it in the frontend.

However, the problem is it seems like the data itself is not reaching the server - when I console.log(req.body) on server it's undefined. I'm totally stumped.

Network tab when I inspect request:

  • Headers status is 200, request completed
  • the Payload shows the json object correctly formatted body: {url: "https://example.com"}
  • the Response returns correctly too! {response: "foo"}

Client-side API function:

const callBackendAPI = async (query) => {
        const response = await axios.post('/', {
            body: { url: query },
        });
    }

Note: I've added "proxy": "http://localhost:3001" to the client's package.json.

In server:

const express = require('express');
const app = express();

app.post('/', (req, res) => {
    console.log(req.body); // <------ **Here's the issue, there's nothing here**
    res.json({ response: 'foo' });
    // however, if I send res.json(req.body), the response is empty in Network tab
});

Solution

  • You can use the body-parser lib:

    Install using: npm install body-parser

    const express = require('express');
    const app = express();
    const bodyParser = require('body-parser')
    app.use(bodyParser.json())
    
    app.post('/', (req, res) => {
        console.log(req.body); // <------ **Here's the issue, there's nothing here**
        res.json({ response: 'foo' });
        // however, if I send res.json(req.body), the response is empty in Network tab
    });
    
    

    Apparently they've added express.json() back since 4.16.0 according to https://github.com/expressjs/express/releases/tag/4.16.0 . So you could also use express.json() without installing body-parser.

    const express = require('express');
    const app = express();
    app.use(express.json())
    
    app.post('/', (req, res) => {
        console.log(req.body); // <------ **Here's the issue, there's nothing here**
        res.json({ response: 'foo' });
        // however, if I send res.json(req.body), the response is empty in Network tab
    });