1

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
});
5
  • 1
    Are you using a body parser Commented Dec 25, 2021 at 3:40
  • FML. no. i'm not. Commented Dec 25, 2021 at 3:42
  • just like this? const bodyParser = require('body-parser'); app.use(bodyParser.urlencoded({ extended: false })); Commented Dec 25, 2021 at 3:42
  • Yeah any config should work Commented Dec 25, 2021 at 3:44
  • 2
    Try with App.use(express.json()); Commented Dec 25, 2021 at 3:50

1 Answer 1

2

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
});

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.