首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >来自RESTful接口的Post请求给出UnhandledPromiseRejectionWarning: ValidationError:产品验证失败:错误

来自RESTful接口的Post请求给出UnhandledPromiseRejectionWarning: ValidationError:产品验证失败:错误
EN

Stack Overflow用户
提问于 2021-09-11 10:58:51
回答 1查看 110关注 0票数 0

我正在使用这个RESTful应用程序接口,我想向服务器发送一个post请求,以便在数据库中创建一个文档。为此,我使用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中发送错误,我正在postman内部测试它。我的代码中有没有bug?我怎么才能解决这个问题。这是我的app.js文件

代码语言:javascript
运行
复制
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')
})

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-09-11 14:04:20

我没有让express读取express格式。这就是它不起作用的原因

我所要添加的就是app.use(express.json()),然后它就可以工作了

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69142335

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档