0

我用于测试我的项目 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);
4

1 回答 1

0

您需要使用 body-parser 来使用带有 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
});

有关它的更多信息,请阅读包文档

于 2019-12-10T20:05:23.957 回答