node.js - API 帖子,空主体对象

标签 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())

我的 Controller :

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

最佳答案

我尝试了与您类似的代码,并且工作正常,请确保您正在点击来自 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}`);
});

关于node.js - API 帖子,空主体对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53101239/

相关文章:

node.js - 链接的 Jade 变量

json - 如何在 POSTMAN 中发送 curl POST 变量

node.js - 如何使用 MongoDB/NodeJS 进行大规模随机更新

node.js - 在 Yeoman 中使用 Node.js 的 module.exports 会产生不同的结果

spring - 如何将时间值从 Postman 发送到我的 REST api

java - Postman 中的 Spring Boot MultiValueMap 参数

azure - 使用 Postman 更新 azure 附加 blob 存储

http - Google Analytics 4 测量协议(protocol)不起作用

node.js - 访问 Express 中间件中的模块实例

php - 在 Nginx 和 Ubuntu 服务器上设置 PHP