失眠中的“无法读取未定义的属性'名称'” POST JSON方法

时间:2019-12-10 19:48:10

标签: node.js json post insomnia

我用于测试我的项目API失眠(例如Postman)程序,当我使用GET方法时都没有问题,但是POST方法返回未定义的req.body.namereq.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);

1 个答案:

答案 0 :(得分:0)

您需要使用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