Tah*_*san 12 json mongodb node.js express postman
我在使用邮递员时遇到一些问题。当我尝试以 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"
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的项目代码片段
产品.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
});
});
});
Run Code Online (Sandbox Code Playgroud)
产品模型.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);
Run Code Online (Sandbox Code Playgroud)
你错过了
app.use(bodyParser.urlencoded({ extended: true }));
Run Code Online (Sandbox Code Playgroud)
然后尝试x-www-form-urlencoded
postman's formdata
被视为multipart/formdata
。您必须使用 multer 或其他类似的库才能解析表单数据。x-www-form-urlencoded
来自raw
邮递员的数据,不需要 multer 进行解析。body-parser
您可以使用或表达内置中间件来解析这些数据express.json()
,express.urlencoded({ extended: false, })
req.body
multer 内部(即 fileFilter)或在 multer 之后的中间件中访问,但如果您没有将 multer 用作全局中间件(这是坏主意),则不能在之前访问。小智 5
使用 multer 中间件:
const upload = require('multer')();
route.post('/', upload.any(), (req, res) => {
// your code...
});
Run Code Online (Sandbox Code Playgroud)
您需要使用主体解析器。
npm install body-parser --save
Run Code Online (Sandbox Code Playgroud)
然后只需添加您的代码
var bodyParser = require('body-parser')
app.use(bodyParser.json())
Run Code Online (Sandbox Code Playgroud)
详细信息可以参见https://www.npmjs.com/package/body-parser
归档时间: |
|
查看次数: |
29396 次 |
最近记录: |