简体   繁体   中英

Express req.query becoming null

I have the following function which purpose will be to clean get parameters for a Restful api:

var clean_query = function(){
    return function(req, res, next){
         console.log(req.query)
         // Do stuff
         next();
    }
}

What is really is strange is when I try this function, here is what I see in the console:

✔ Express server listening on port 3000 in development mode
✔ MongoDB connection done.
✔ Server launched

{ param1: 'toto', param2: 'titi' }

/Users/... console.log(req.query)
                          ^
TypeError: Cannot read property 'query' of null

The error message is pretty clear : it tells me req is null.... But if you check console output, you can see that console.log(req.query) is outputing the content to the console so it is not empty in reality.

Do you know what can be my mistake?

EDIT : my route handling:

app.get(uri, clean_query(), get_list_func(schema));

EDIT 2 : My middlewares:

app.use(express.logger('dev'));
app.use(express.methodOverride());
app.use(express.bodyParser());
app.use(express.urlencoded());
app.use(express.json());
app.use(expressValidator());
app.use(express.cookieParser('secret'));
app.use(express.session( {
    store  : MongoStore( { db : 'dbtest' } ),
    key    : 'sessionid',
    cookie : { httpOnly : false },
    secret : 'secret'
}, function() {
    app.use(app.router);
}));
app.use(passport.initialize());
app.use(passport.session());

EDIT 3 : strange if i remove next from function parameter, there is no more error but i can't use the function like that as i need to chain it with other controllers.

EDIT 4 : Wow, it seems that this function is called twice.... First time it is called req is ok, second time it is null. it must have something to do with next().

In the context where you define the function that will be returned there is no "req, res, next" defined. So it is expected that the req would be null.

You don't need to return a function in clean_query . You can just define clean_query as a middleware function as follows to resolve the issue.

var clean_query = function(req, res, next){
     console.log(req.query)
     // Do stuff
     next();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM