我在使用 Postman 时遇到了一些问题。当我尝试以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
下面是我的项目代码片段
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);
6条答案
按热度按时间ymdaylpp1#
你失踪了
然后尝试
x-www-form-urlencoded
dm7nw8vv2#
使用multer中间件:
r9f1avp53#
postman's formdata
发送的任何数据都被视为multipart/formdata
。你必须使用multer或其他类似的库来解析表单数据。x-www-form-urlencoded
和raw
数据,不需要使用multer进行解析。您可以使用body-parser
或express内置中间件express.json()
和express.urlencoded({ extended: false, })
解析这些数据req.body
(即fileFilter),或者在multer之后的中间件中访问req.body
,但如果你没有使用multer作为全局中间件(这是个坏主意),就不能在multer之前访问req.body
。对于代码段:https://stackoverflow.com/a/68588435/10146901
kiz8lqtg4#
你需要使用body-parser。
然后只要加上你的代码
详细信息可在https://www.npmjs.com/package/body-parser中找到
c9x0cxw05#
除了使用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。尝试使用该软件包。
gorkyyrv6#
https://www.npmjs.com/package/multer