我用于测试我的项目 API Insomnia(如邮递员)程序,当我使用 GET 方法时一切正常,但 POST 方法返回未定义req.body.name
并且req.body.price
,我捕获的这个错误,这是我的请求
查询
这是我的 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);