作者:zhongxiaomin1981 | 来源:互联网 | 2023-06-01 16:59
我用于测试我的项目API失眠(例如Postman)程序,当我使用GET方法时都没有问题,但是POST方法返回未定义的req.body.name
和req.body.price
,
我抓住的这个error是我的要求
query
这是我的app.js
const express = require('express');
const app = express();
const morgan = require('morgan');
const mOngoose= require('mongoose');
require('dotenv').config()
mongoose.connect(`mongodb+srv://vadim:${process.env.MONGO_ATLAS_PS}@cluster0-abuqs.mongodb.net/shop`,{
useNewUrlParser: true,useUnifiedTopology: true
});
const productRoutes = require('./api/routes/
app.use(morgan('dev'));
app.use('/products',productRoutes);
module.exports = app;
这是我的products.js路由器
const express = require('express');
const router = express.Router();
const mOngoose= require('mongoose');
const Product = require('../models/product')
router.post("/",(req,res,next) => {
console.log(JSON.stringify(req.body))
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: "Handling POST requests to /products",createdProduct: result
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
});
product.js的模型
const mOngoose= require('mongoose');
const productSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,name: String,price: Number
});
module.exports = mongoose.model('Product',productSchema);
您需要使用body解析器通过express的POST方法捕获数据。
首先,您需要安装它:
npm install body-parser --save
然后在您的代码中:
const express = require('express');
const router = express.Router();
const mOngoose= require('mongoose');
const Product = require('../models/product');
const bodyParser = require('body-parser');
express.use(bodyParser.json());
express.post("/",(req,res,next) => {
console.log(JSON.stringify(req.body))
const product = new Product({
_id: new mongoose.Types.ObjectId(),name: req.body.name,price: req.body.price
});
//The rest of your code
});
有关更多信息,read the package docs。