app.use(validator()); ^ TypeError: validator is no

2020-07-27 05:07发布

问题:

I am working on a project for my summer training and I was asked to create a login page using Node.js however, after installing express-validator and entered the codes I suppose to in the app.js file it prints out an error each time I run the app.js or the www in the bin file telling me "validator is not a function".

And most importantly, I am using WebStorm as my IDE on Windows.

This is the error it prints out;

app.use(validator());
        ^
TypeError: validator is not a function

Here is the code from the app.js file;

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var validator = require('validator');
var session = require('session');


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

var app = express();

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

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(validator());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({secret:'max', saveUninitialize: false, resave: false}));

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

module.exports = app;

回答1:

Uninstall the current version: npm uninstall express-validator.

And install the older version: npm install express-validator@5.3.1.



回答2:

From what I can tell, you're using the wrong module. The validator module exports an object with a bunch of validation methods on it. So, your validator is just an object, not something that can be used as Express middleware.

Perhaps, you want to use the Express validator module which is designed to work as middleware?



回答3:

I had your problem too ، Replacing ^ 5.1.2 will replace version 6 the problem resolve. The problem is how the package is configured

at package json "express-validator": "^5.1.2",

npm i