简体   繁体   中英

Node JS POST request returning undefined body

Quite new to Node JS and I am trying to post to a specific URL and retrieve the data.

I am using postman to do this but every time I post to it the response data is undefined but the status code is 200.

I have added body-parse as suggested but still no joy.

I will post my server code and request below.

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

const app = express();
const port = process.env.PORT || 5000;

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.get('/api/hello', (req, res) => {
    res.send({ express: 'Hello From Express' });
});

app.post('/api/save-json', (req, res) => {
    console.log(req);
    res.send(
        `I received your POST request. This is what you sent me: ${req.body.json}`,
    );
});

app.listen(port, () => console.log(`Listening on port ${port}`));

My postman request is:

{
    "body" : 
    {
        "json": "some data"
    }
}

Any ideas?

body是包含 HTTP 请求正文(由body-parser设置)的req对象中的属性,因为您发送的是一个名为body的对象,您需要像这样访问它: req.body.body.json

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM