【问题标题】:Postman raw data works but form-data not works on POST request in node邮递员原始数据有效,但表单数据不适用于节点中的 POST 请求
【发布时间】:2018-07-21 10:37:00
【问题描述】:

我在使用邮递员时遇到了一些问题。当我尝试以 JSON(application/json) 格式发送原始数据时,它会成功。

Postman sending post request and succeded

但是当我尝试发送表单数据时,它会返回一些错误。

{
    "error": {
        "errors": {
            "name": {
                "message": "Path `name` is required.",
                "name": "ValidatorError",
                "properties": {
                    "message": "Path `{PATH}` is required.",
                    "type": "required",
                    "path": "name"
                },
                "kind": "required",
                "path": "name",
                "$isValidatorError": true
            },
            "price": {
                "message": "Path `price` is required.",
                "name": "ValidatorError",
                "properties": {
                    "message": "Path `{PATH}` is required.",
                    "type": "required",
                    "path": "price"
                },
                "kind": "required",
                "path": "price",
                "$isValidatorError": true
            }
        },
        "_message": "Product validation failed",
        "message": "Product validation failed: name: Path `name` is required., price: Path `price` is required.",
        "name": "ValidationError"
    }
}

Postman errors

这是我的项目代码sn-ps

product.js

import express from 'express';
import mongoose from 'mongoose';
import Product from '../models/product.model';

router.post('/', (req, res, next) => {
    const product = new Product({
        _id: new mongoose.Types.ObjectId(),
        name: req.body.name,
        price: req.body.price
    });
    product.save().then(result => {
        console.log(result);
        res.status(201).json({
            message: 'Created product successfully',
            createdProduct: {
                name: result.name,
                price: result.price,
                _id: result._id,
                request: {
                    type: 'GET',
                    url: `http://localhost:3000/products/${result._id}`
                }
            }
        });
    }).catch(err => {
        console.log(err);
        res.status(500).json({
            error: err
        });
    });
});

product.model.js

import mongoose from 'mongoose';

const productSchema = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    name: {type: String, required: true},
    price: {type: Number, required: true}
});

module.exports = mongoose.model('Product', productSchema);

【问题讨论】:

    标签: json node.js mongodb express postman


    【解决方案1】:

    你错过了

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

    那就试试x-www-form-urlencoded

    【讨论】:

    • x-www-form-urlencoded 有效,但 form-data 无效
    • 您找到解决方案了吗?我的也适用于 x-www-form-urlencoded 但不适用于 form-data
    • 这对我有用,但数据以一种奇怪的格式出现,几乎就像部分 JSON。我的第一个数组用双引号括起来,但它的关键不是。我的第二个数组用单引号括起来,键也是对象键,而不是字符串。
    【解决方案2】:

    你需要使用body-parser。

    npm install body-parser --save
    

    然后只需添加您的代码

    var bodyParser = require('body-parser')
    
    app.use(bodyParser.json())
    

    详情可见https://www.npmjs.com/package/body-parser

    【讨论】:

    • 对不起!我在 product.js 上有一个文件重复。我只是删除了那个文件,现在它对我有用。感谢您的回复。 :)
    • 我没有任何重复的文件,然后我也收到错误消息。当我尝试使用表单数据时会发生这种情况,如果我尝试使用行数据,它会给出正确的输出。但是当我提供表单数据时,它会显示错误。
    【解决方案3】:

    使用 multer 中间件:

    const upload = require('multer')();
    
    route.post('/', upload.any(), (req, res) => {
        // your code...
    });
    

    【讨论】:

      【解决方案4】:

      除了使用 body-parser 之外,它仍然会返回空的 req.body ,这会导致错误,因为您已经进行了验证。使用 form-data tru Postman 发送 POST 请求时返回空 req.body 的原因是因为 body-parser 无法处理 multipart/form-data。您需要一个可以像 multer 一样处理多部分/表单数据的包。见https://www.npmjs.com/package/multer。尝试使用该软件包。

      【讨论】:

        【解决方案5】:
        • 使用postman's formdata 发送的任何数据都被视为multipart/formdata。您必须使用 multer 或其他类似的库来解析表单数据。
        • 对于来自邮递员的x-www-form-urlencodedraw 数据不需要multer 进行解析。您可以使用body-parser 或表达内置中间件express.json()express.urlencoded({ extended: false, }) 来解析这些数据
        • 由于 multer 返回一个中间件,您只能在 multer(即 fileFilter)或 multer 之后的中间件中访问req.body,如果您没有使用 multer 作为全局中间件(这是个坏主意),则不能在之前访问。

        对于代码 sn-ps:https://stackoverflow.com/a/68588435/10146901

        【讨论】:

          【解决方案6】:
          • 使用multer获取表单数据

          • 在上传功能中,您可以从表单数据中获取 req.body

          https://www.npmjs.com/package/multer

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2015-03-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-11-23
            • 1970-01-01
            • 2021-11-17
            • 2019-07-03
            相关资源
            最近更新 更多