【问题标题】:Is there something wrong with this post request?这个帖子请求有问题吗?
【发布时间】:2020-10-17 14:05:48
【问题描述】:

下面是我编写的用于检查 POST 是否可以进入数据库的代码。 鉴于 Postman 的请求:

localhost:8080/api/users?email=user@website.com&password=notpassword&phoneNumber=0987654321

当 Postman 发送 POST 并被节点捕获时,查询为空。我不确定发生了什么。

import express from 'express';
import bodyParser from 'body-parser';
import db from './db/db';

const app = express();
const PORT = 8080;
const jsonParser = bodyParser.json();

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

app.get('/api/users', (req, res) => {
    res.status(200).send({
        success: 'true',
        message: 'users retrieved successfully.',
        users: db
    });
});

app.post('/api/users', jsonParser, (req, res) => {
    if (!req.body.email) {
        return res.status(400).send({
            success: 'false',
            message: 'An e-mail is required.'
        });
    } else if (!req.body.password) {
        return res.status(400).send({
            success: 'false',
            message: 'A password is required.'
        });
    } else if (!req.body.phoneNumber) {
        return res.status(400).send({
            success: 'false',
            message: 'A phone number is required.'
        });
    } else if (req.body.phoneNumber.len() !== 10) {
        return res.status(400).send({
            success: 'false',
            message: 'The phone number must be 10 digits long, no dashes. (##########)'
        });
    }
    const user = {
        id: db.length + 1,
        email: req.body.email,
        password: req.body.password,
        phoneNumber: req.body.phoneNumber
    }
    db.push(user);
    return res.status(201).send({
        success: 'true',
        message: 'User added successfully.',
        user
    });
    console.log(req.body)
});

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

我真的想不出任何其他方式来解决我的问题,除了“为什么 Postman 查询带有参数发送并被节点捕获为空?”

【问题讨论】:

  • 这些值不在 body 中,它们是查询参数。但是为什么不把它们放在体内呢?另请注意,您也可以 app.use 使用 JSON 解析器。
  • 我在你放下的时候捡起来,但我不知道具体该怎么做......
  • 哪一部分?如果您想访问查询参数,请阅读 Express 文档。如果您想发送请求正文,请阅读 Postman 文档。

标签: node.js express postman body-parser


【解决方案1】:

正如u/jonrsharpe 所述,我没有使用 Postman 选项在请求中发送正文,仅使用参数。阅读文档是必需的:POST request in Postman

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多