api帖子,空物体

时间:2018-11-01 12:25:28

标签: node.js postman

当我发布自己的详细信息时,我试图使用node和'body-parser'设置基本API:

localhost:3000/users?email=test.com&givenName=test

我的req.body.email为空,如何发布我的详细信息?我正在像这样使用body-parser

// create express app
const app = express();

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }))

// parse application/json
app.use(bodyParser.json())

我的控制器:

exports.create = (req, res) => {
    // Validate request
    if (!req.body.email) {
        return res.status(400).send({
            message: "user cannot be empty"
        });
    }

    // Create a user
    const user = new user({
        email: req.body.email || "No Emails",
        givenName: req.body.givenName || "No Emails",
        familyName: req.body.familyName || "No Emails"
    });

    // Save user in the database
    user
        .save()
        .then(data => {
            res.send(data);
        })
        .catch(err => {
            res.status(500).send({
                message:
                    err.message ||
                    "Some error occurred while creating the user."
            });
        });
};

2 个答案:

答案 0 :(得分:0)

我尝试了与您的代码相似的代码,并且工作正常,请确保您符合Postman的POST请求。参见下面的代码,

'use strict';

// Initialize an Express application
const express = require('express');
const app = express();
const port = 8080;

// parse application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));

// parse application/json
app.use(express.json());

app.use((req, res) => {
    console.log(req.body);
    res.json(res.body);
});

// Start the express application
app.listen(port, () => {
    console.log(`server listening on port ${port}`);
});

答案 1 :(得分:0)

也许我错了,但是您将bodyquery混在一起了吗?因此,可能有两个原因:

1。)没有将bodyquery混在一起,但是缺少了body

您的请求应类似于以下语句:

curl -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{"email":"test.com","givenName":"test","familyName":"test"}' 'localhost:3000/users'

之后,您可以通过req.body.emailreq.body.givenNamereq.body.familyName访问这些值。

2。)混合使用bodyquery

通过req.query.emailreq.query.givenName以及正确的req.query.familyName访问您的值。