gpt4 book ai didi

json - postman 原始数据有效,但表单数据不适用于 Node 中的 POST 请求

转载 作者:行者123 更新时间:2023-12-03 12:14:43 25 4
gpt4 key购买 nike

我在使用 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);

最佳答案

你错过了

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

然后试试 x-www-form-urlencoded

关于json - postman 原始数据有效,但表单数据不适用于 Node 中的 POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48726473/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com