2016-11-14 65 views
0

我收到提示req.checkBody不是一個函數以爲我已經包括expressvalidator和bodyparser ..類型錯誤:req.checkBody不包括bodyparser和expressvalidator模塊的功能

這裏是我的代碼

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 is not a function

+1

嘗試包括在'index.js'快遞驗證器。 –

+0

試過但沒有工作。 –

+0

@ stdob--我剛剛插入函數直接檢查函數的工作,但得到相同的錯誤 –

回答

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

     }); 

    });