繁体   English   中英

邮递员原始数据有效,但表单数据不适用于节点中的 POST 请求

[英]Postman raw data works but form-data not works on POST request in node

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

邮递员发送邮件请求并成功

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

{
    "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"
    }
}

邮差错误

这是我的项目代码片段

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

产品模型.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);

你错过了

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

然后尝试x-www-form-urlencoded

您需要使用正文解析器。

npm install body-parser --save

然后只需添加您的代码

var bodyParser = require('body-parser')

app.use(bodyParser.json())

详细信息可以在https://www.npmjs.com/package/body-parser找到

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

// 使用multer作为中间件,使用upload.any()方法解决问题。

    const multer = require('multer);

    const upload = multer();


    route.post('/' , upload.any(), (req,res) => {
              
                 // your code...
    });
  • 使用multer获取表单数据

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

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

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

代码片段: https : //stackoverflow.com/a/68588435/10146901

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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