1

我已经尝试解决这个问题 2 个小时了,我有点沮丧。基本上,我想验证表单输入,但我总是收到此错误。

TypeError: req.checkBody is not a function
at C:\Users\bobbo\Desktop\Develops\Project_folder\routes\index.js:19:7
at Layer.handle [as handle_request] (C:\Users\bobbo\Desktop\Develops\Project_folder\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\bobbo\Desktop\Develops\Project_folder\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\bobbo\Desktop\Develops\Project_folder\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\bobbo\Desktop\Develops\Project_folder\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\bobbo\Desktop\Develops\Project_folder\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\bobbo\Desktop\Develops\Project_folder\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\bobbo\Desktop\Develops\Project_folder\node_modules\express\lib\router\index.js:275:10)
at Function.handle (C:\Users\bobbo\Desktop\Develops\Project_folder\node_modules\express\lib\router\index.js:174:3)
at router (C:\Users\bobbo\Desktop\Develops\Project_folder\node_modules\express\lib\router\index.js:47:12)

几乎我能找到的唯一信息是告诉我写app.use(expressValidator()); after app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false }));,但不管我做什么,我仍然得到同样的错误。这是我使用的代码。

//index.js    
    var express = require('express');
    var bodyParser = require('body-parser');
    var app = express();
    var expressValidator = require('express-validator');

    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(expressValidator());
    var router = express.Router();
    router.get('/', function(req, res, next) {
      res.render('index', { title: 'Express' });
    });

    router.get('/signup', function(req, res, next) {
      res.render('signup', { title: 'Express' });
    });

    router.post('/signup', function(req, res){
      var name = req.body.name;
      console.log(name);    //works
      req.checkBody("name", "Invalid name").notEmpty();
      var errors = req.validationErrors();
      if(errors){
        console.log('errors');
      } else{
        console.log('no errors');
      }
    });
    module.exports = router;

应用程序.js

//app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var bodyParser = require('body-parser');
var expressValidator = require('express-validator');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

// BodyParser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

包.json

    //package.json
{
  "name": "pizzaonline",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "body-parser": "^1.18.3",
    "cookie-parser": "~1.4.3",
    "debug": "~2.6.9",
    "express": "~4.16.0",
    "express-session": "^1.15.6",
    "express-validator": "^5.2.0",
    "http-errors": "~1.6.2",
    "morgan": "~1.9.0",
    "pug": "2.0.0-beta11"
  }

}

如果我注释掉req.checkBody("name", "Invalid name").notEmpty();,下一个要执行的快速验证代码是var errors = req.validationErrors();,给我一个相同的错误,告诉我req.validationErrors()不是一个函数。我是新手,但这告诉我 express-validator 没有正确安装,我错了吗?任何帮助深表感谢。提前致谢。

4

2 回答 2

2

在您的嵌套路由文件(index.jsusers.js)中,您正在创建新的应用程序实例并将该验证器附加到它实际上是不正确的。

原因是创建新的应用程序实例您创建了不同于appin 的新应用程序上下文app.js

所以这里是修复:

app.js1)在文件中的此行上方附加快速验证器:

app.use(expressValidator());


app.use('/', indexRouter);
app.use('/users', usersRouter);

2)app从嵌套路由文件中删除对象生成,并使其看起来像:

//index.js    
var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

router.get('/signup', function(req, res, next) {
  res.render('signup', { title: 'Express' });
});

router.post('/signup', function(req, res){
  var name = req.body.name;

  req.checkBody("name", "Invalid name").notEmpty();
  var errors = req.validationErrors();
  if(errors){
    console.log('errors');
  } else{
    console.log('no errors');
  }
});

module.exports = router;
于 2018-05-15T21:03:19.683 回答
-1
npm i --save express-validator@4

reqiure app.js

app.use(expressValidator());

然后再试一次

npm start
于 2019-07-09T08:38:33.070 回答