【问题标题】:Post request from RESTful API giving UnhandledPromiseRejectionWarning: ValidationError: Product validation failed: error来自 RESTful API 的发布请求给出 UnhandledPromiseRejectionWarning:ValidationError:产品验证失败:错误
【发布时间】:2021-11-07 13:05:16
【问题描述】:

我正在使用这个 RESTful api,我想向服务器发送一个发布请求以在数据库中创建一个文档。为此,我正在使用 model.create 方法。但它让我在控制台中发送错误 UnhandledPromiseRejectionWarning: ValidationError: Product validation failed: seller: Please enter product seller, category: Please enter the product category, description: Please enter product description, name: Please enter product name我正在邮递员内部测试这个。 我的代码中是否有任何错误?我怎样才能解决这个问题。 这是我的 app.js 文件

const express = require('express')
const mongoose = require('mongoose') 
const bodyParser = require("body-parser");

const app = express()
app.use(bodyParser.urlencoded({extended: true}));
mongoose.connect('mongodb://localhost:27017/playDB', {useNewUrlParser: true, useUnifiedTopology: true})

const playSchema = new mongoose.Schema({
    name: {
        type: String,
        required: [true, 'Please enter product name'],
    },
    price : {
        type: Number,
        required: [true, 'Please enter product price'],
    },
    description: {
        type: String,
        required: [true, 'Please enter product description']
    },
    category: {
        type: String,
        required: [true, 'Please enter the product category'],
    },
    seller: {
        type: String,
        required: [true, 'Please enter product seller']
    },
    stock: {
        type: Number,
        required: [true, 'Please enter product stock'],
    }
})

const Product = mongoose.model('Product', playSchema)

//get all products

app.route("/products")
        .post(async function(req, res, next){
          const product = await Product.create(req.body);

          res.send({
              success: true,
              product
          })
            
        })


app.listen(3000, function(){
    console.log('server is running')
})

【问题讨论】:

  • 添加这个顶部的app.route app.use(bodyParser.json());
  • @mohammadNaimi 我试过了,它不起作用:((
  • 你能记录你的 req.body 吗?
  • @mohammadNaimi 是的。我找到了答案。我没有编码 app.use(express.json())。现在代码可以工作了

标签: javascript mongodb api express mongoose


【解决方案1】:

我没有制作 express 阅读 express 格式。所以这就是为什么它不起作用

我只需要添加app.use(express.json()) 然后它就起作用了

【讨论】:

    猜你喜欢
    • 2023-02-24
    • 1970-01-01
    • 2019-02-25
    • 2017-10-29
    • 1970-01-01
    • 2014-03-28
    • 2018-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多