Cerulean
Cerulean

Reputation: 6033

req.checkBody is not a function

I'm following along with the Mozilla Express tutorial (https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/forms) and have reached the part using express-validator. When I submit a form whose contents are validated using express-validator I keep getting the error "req.checkBody is not a function" (and if I remove the line that generates that, I get other errors, like "req.sanitize is not a function"). It seems that express-validator is not being recognized properly. I am using node v6.3.1 for whatever it's worth.

express-validator is installed

├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
└── [email protected]

I load it in the main app file (app.js)

var expressValidator = require('express-validator');

and apply it a few lines below that

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(expressValidator()); // Add this after the bodyParser middlewares!

app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

and try to make use of it in another module (genreController.js)

exports.genre_create_post = function(req, res, next) {

    //Check that the name field is not empty
    req.checkBody('name', 'Genre name required').notEmpty(); 

    //Trim and escape the name field. 
    req.sanitize('name').escape();
    req.sanitize('name').trim();

    //Run the validators
    var errors = req.validationErrors();

Where am I going wrong? I've installed it and de-installed it, I've removed the code from the modules and re-entered it, but to no avail.

  req.checkBody is not a function
    TypeError: req.checkBody is not a function
        at exports.genre_create_post (/Users/cerulean/Documents/Projects/express-locallibrary-tutorial/controllers/genreController.js:48:9)
        at Layer.handle [as handle_request] (/Users/cerulean/Documents/Projects/express-locallibrary-tutorial/node_modules/express/lib/router/layer.js:95:5)
        at next (/Users/cerulean/Documents/Projects/express-locallibrary-tutorial/node_modules/express/lib/router/route.js:137:13)
        at Route.dispatch (/Users/cerulean/Documents/Projects/express-locallibrary-tutorial/node_modules/express/lib/router/route.js:112:3)
        at Layer.handle [as handle_request] (/Users/cerulean/Documents/Projects/express-locallibrary-tutorial/node_modules/express/lib/router/layer.js:95:5)
        at /Users/cerulean/Documents/Projects/express-locallibrary-tutorial/node_modules/express/lib/router/index.js:281:22
        at Function.process_params (/Users/cerulean/Documents/Projects/express-locallibrary-tutorial/node_modules/express/lib/router/index.js:335:12)
        at next (/Users/cerulean/Documents/Projects/express-locallibrary-tutorial/node_modules/express/lib/router/index.js:275:10)
        at Function.handle (/Users/cerulean/Documents/Projects/express-locallibrary-tutorial/node_modules/express/lib/router/index.js:174:3)
        at router (/Users/cerulean/Documents/Projects/express-locallibrary-tutorial/node_modules/express/lib/router/index.js:47:12)
        at Layer.handle [as handle_request] (/Users/cerulean/Documents/Projects/express-locallibrary-tutorial/node_modules/express/lib/router/layer.js:95:5)
        at trim_prefix (/Users/cerulean/Documents/Projects/express-locallibrary-tutorial/node_modules/express/lib/router/index.js:317:13)
        at /Users/cerulean/Documents/Projects/express-locallibrary-tutorial/node_modules/express/lib/router/index.js:284:7
        at Function.process_params (/Users/cerulean/Documents/Projects/express-locallibrary-tutorial/node_modules/express/lib/router/index.js:335:12)
        at next (/Users/cerulean/Documents/Projects/express-locallibrary-tutorial/node_modules/express/lib/router/index.js:275:10)
        at /Users/cerulean/Documents/Projects/express-locallibrary-tutorial/node_modules/express/lib/router/index.js:635:15
        at next (/Users/cerulean/Documents/Projects/express-locallibrary-tutorial/node_modules/express/lib/router/index.js:260:14)
        at Function.handle (/Users/cerulean/Documents/Projects/express-locallibrary-tutorial/node_modules/express/lib/router/index.js:174:3)
        at router (/Users/cerulean/Documents/Projects/express-locallibrary-tutorial/node_modules/express/lib/router/index.js:47:12)
        at Layer.handle [as handle_request] (/Users/cerulean/Documents/Projects/express-locallibrary-tutorial/node_modules/express/lib/router/layer.js:95:5)
        at trim_prefix (/Users/cerulean/Documents/Projects/express-locallibrary-tutorial/node_modules/express/lib/router/index.js:317:13)
        at /Users/cerulean/Documents/Projects/express-locallibrary-tutorial/node_modules/express/lib/router/index.js:284:7

Upvotes: 2

Views: 2263

Answers (3)

oudekaas
oudekaas

Reputation: 1

I had the same problem, in my case I solved it by making sure that in App.js the app.use(expressValidator()) is behind the app.use.bodyParser and I made sure that the routes are after the bodyparser and app.use(express.static......) I think it has to do with the order in which the elements are put.

In my case the order that seemed to work:

viewengine

BodyParser Middleware

routes

static folder

app.use express validator

Before using this order Checkbody wasn’t present as a function, but could for instance use function Body. So req. seemed to work but not for all functions.

If ayone can explan better please do :)

Upvotes: 0

Cerulean
Cerulean

Reputation: 6033

I got it to work but I don't know why. If anyone can help me understand it, I'd appreciate the info. I tracked down the answer when I removed the validator code (just to move on in the project) and then noticed that

req.body

was undefined

Googled an answer for this and it involved moving the routes further down in the setup, so I tried that.

I moved

app.use('/', index);
    app.use('/users', users);
    app.use('/catalog', catalog);  // Add catalog routes to middleware chain.

below

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

    // 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(expressValidator()); // Add this after the bodyParser middlewares!
app.use(cookieParser());
    app.use(express.static(path.join(__dirname, 'public')));

and all works fine.

Upvotes: 0

thiagoh
thiagoh

Reputation: 7398

Maybe is the way you're using require in your code. As you haven't inserted the part of the code that does that I'm assuming a few items. Anyway, you can check a working code and figure out what you've done wrong. OR, paste the whole code here and I'll be able to help you.

try this

// index.js

var util = require('util'),
    logger = require('morgan'),
    bodyParser = require('body-parser'),
    cookieParser=require('cookie-parser'),
    express = require('express'),
    expressValidator = require('express-validator'),
    app = express();

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(expressValidator()); // this line must be immediately after any of the bodyParser middlewares! 
app.use(cookieParser());
// app.use(express.static(path.join(__dirname, 'public')));

app.get('/genres', require('./genre-controller.js').genre_create_post);

app.listen(8888);

and genre-controller.js

// genre-controller.js
exports.genre_create_post = function (req, res, next) {

    console.log('my get method response');

    //Check that the name field is not empty
    req.checkBody('name', 'Genre name required').notEmpty();

    //Trim and escape the name field. 
    req.sanitize('name').escape();
    req.sanitize('name').trim();

    //Run the validators
    var errors = req.validationErrors();

    res.end(errors);
};

the package.json is

{
  "name": "44836938-req-checkbody-is-not-a-function",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "dependencies": {
    "body-parser": "^1.17.2",
    "cookie-parser": "^1.4.3",
    "express": "^4.15.3",
    "express-validator": "^3.2.0",
    "morgan": "^1.8.2"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

then run

$ npm install
$ node index.js

and go to http://localhost:8888/genres and you'll see the validator working.. the error will be something like this

TypeError: first argument must be a string or Buffer
    at ServerResponse.OutgoingMessage.end (_http_outgoing.js:549:11)
    at exports.genre_create_post (/home/projects/44836938-req-checkbody-is-not-a-function/genreController.js:15:9)
    at Layer.handle [as handle_request] (/home/projects/44836938-req-checkbody-is-not-a-function/node_modules/express/lib/router/layer.js:95:5)
    at next (/home/projects/44836938-req-checkbody-is-not-a-function/node_modules/express/lib/router/route.js:137:13)
    at Route.dispatch (/home/projects/44836938-req-checkbody-is-not-a-function/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/home/projects/44836938-req-checkbody-is-not-a-function/node_modules/express/lib/router/layer.js:95:5)
    at /home/projects/44836938-req-checkbody-is-not-a-function/node_modules/express/lib/router/index.js:281:22
    at Function.process_params (/home/projects/44836938-req-checkbody-is-not-a-function/node_modules/express/lib/router/index.js:335:12)
    at next (/home/projects/44836938-req-checkbody-is-not-a-function/node_modules/express/lib/router/index.js:275:10)
    at cookieParser (/home/projects/44836938-req-checkbody-is-not-a-function/node_modules/cookie-parser/index.js:70:5)
    at Layer.handle [as handle_request] (/home/projects/44836938-req-checkbody-is-not-a-function/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (/home/projects/44836938-req-checkbody-is-not-a-function/node_modules/express/lib/router/index.js:317:13)
    at /home/projects/44836938-req-checkbody-is-not-a-function/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (/home/projects/44836938-req-checkbody-is-not-a-function/node_modules/express/lib/router/index.js:335:12)
    at next (/home/projects/44836938-req-checkbody-is-not-a-function/node_modules/express/lib/router/index.js:275:10)
    at /home/projects/44836938-req-checkbody-is-not-a-function/node_modules/express-validator/lib/express_validator.js:445:5

Upvotes: 2

Related Questions