我收到错误req.checkBody不是我认为已包含express-validator和body-parser的函数。

这是我的代码

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var expressValidator = require('express-validator');

app.use(bodyParser.urlencoded({ extended: true }));

app.get('/',function(req,res){
    res.sendFile(__dirname +'/index.html')
});

app.post('/',function(req,res){
        req.checkBody("name", "Invalid company").notEmpty();

        var errors = req.validationErrors();
        if (errors) {
            res.status(400).send({ "message": "Missing parameter" });
            // res.send('There have been validation errors: ' + util.inspect(errors), 400);
            return;
        }
        var company = new companySchema(req.body);
        company.save(function(err) {
            if (err) {
                if (err.code === 11000) {
                    return res.status(409).send({ "message": "Company already exist!" });
                }
                return res.status(400).send({ "message": "Server Error!", "err": err });
            }

            return res.status(200).send({ "message": "New company has added!" });

        });

    });

app.listen('3000');
console.log('listening on 3000!')


包含编辑部分的index.html以供参考

index.html

<html>
<body>
 <form method = "post" action="http://localhost:3000">
    <label for="fname">Company name</label>
    <input type="text" id="fname" name="name">
    <input type="submit" value="Submit">
  </form>
</body>
</html>


我得到的错误是


  TypeError:req.checkBody不是函数

最佳答案

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var expressValidator = require('express-validator');

app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressValidator());  //this line to be addded

app.get('/',function(req,res){
    res.sendFile(__dirname +'/index.html')
});

app.post('/',function(req,res){
        req.checkBody("name", "Invalid company").notEmpty();

        var errors = req.validationErrors();
        if (errors) {
            res.status(400).send({ "message": "Missing parameter" });
            // res.send('There have been validation errors: ' + util.inspect(errors), 400);
            return;
        }
        var company = new companySchema(req.body);
        company.save(function(err) {
            if (err) {
                if (err.code === 11000) {
                    return res.status(409).send({ "message": "Company already exist!" });
                }
                return res.status(400).send({ "message": "Server Error!", "err": err });
            }

            return res.status(200).send({ "message": "New company has added!" });

        });

    });

09-25 18:36