猫鼬必须为true req.body.name {}

时间:2020-01-21 17:07:04

标签: node.js express

如果将required设置为false,它将在MongoDB数据库中成功创建一个具有一个ID的对象。有时我会感到困惑,如果需要,请查看我的个人资料。我认为这是一件小事。如果您需要更多信息,请发表评论。

app.js

var express = require('express');
var bodyParser = require('body-parser');
var product = require('./routes/product'); // Imports routes for the products
var app = express();
var mongoose = require('mongoose'); // Set up mongoose connection

var dev_db_url = 'mongodb://localhost/Product';
var mongoDB = process.env.MONGODB_URI || dev_db_url;
mongoose.connect(mongoDB, {useNewUrlParser: true, useUnifiedTopology: true});
mongoose.Promise = global.Promise;
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use('/products', product);


var port = 3002;

app.listen(port, () => {
    console.log('Server is up on port numbner ' + port);
});

model.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var ProductSchema = new Schema({
    name: {type: String, required: true, max: 100},
    price: {type: Number, required: true},
});

module.exports = mongoose.model('Product', ProductSchema);

controller.js

var Product = require('../models/product');

//Simple version, without validation or sanitation
exports.test = function (req, res) {
    res.send('Greetings from the Test controller!');
};

exports.product_create = function (req, res, next) {
    var product = new Product(
        {
            name: req.body.name,
            bags: req.body.bags
        }
    );
    console.log(JSON.stringify(req.body))
    product.save(function (err) {
        if (err) {
            return next(err);
        }
        res.send('Bags Created successfully')
    })
};

router.js

var express = require('express');
var router = express.Router();

// Require the controllers WHICH WE DID NOT CREATE YET!!
var product_controller = require('../controllers/product');

// a simple test url to check that all of our files are communicating correctly.
router.get('/test', product_controller.test);


router.post('/create', product_controller.product_create);

module.exports = router;

HTTP POST:http://localhost:3002/products/create?name=Jorge&price=20

ValidationError:产品验证失败:名称:路径name为 必填

可以帮忙吗? 谢谢!

1 个答案:

答案 0 :(得分:1)

?错误的原因,因为您的req.body.name为空或空。为什么它为空,空或未定义?因为您没有在自己的身体中添加data,所以在您发送创建请求时。

您可以看到您的端点:

HTTP POST:http://localhost:3002/products/create?name=Jorge&price=20

这与req.body无关,而是req.params。因此,您可以使用req.params.namereq.params.price

?️‍♂️因此,如果您使用的是准伞兵传递数据,那么您的code将会像这样:

exports.product_create = function (req, res, next) {
    var product = new Product(
        {
            name: req.params.name,
            price: req.params.price
        }
    );
    console.log(req.params);
    product.save(function (err) {
        if (err) {
            return next(err);
        }
        res.send('Bags Created successfully')
    })
};

如果要使用req.body,则在使用Postman的情况下,请将json对象添加到body

?️‍♂️您可以看到下图:在将create请求发送到后端之前,使用邮递员将数据传递到正文中的示例

enter image description here

因此,如果您要从身体传递数据,那么您的code将会像这样:

exports.product_create = function (req, res, next) {
    var product = new Product(
        {
            name: req.body.name,
            price: req.body.price
        }
    );
    console.log(req.body);
    product.save(function (err) {
        if (err) {
            return next(err);
        }
        res.send('Bags Created successfully')
    })
};

我希望它能为您提供帮助。