TypeError:req.checkBody不是包含bodyparser和expressvalidator模块的函数

时间:2016-11-14 07:09:06

标签: javascript html node.js express request

我收到错误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不是函数

1 个答案:

答案 0 :(得分:2)

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!" });

        });

    });