rg88
rg88

Reputation: 20977

Express not finding redis results it expects

I followed an express demo that has you storing values with redis and then retrieving them. When I tried to adapt that code to the express app I have set up I fail to get the expected results.

Mainly, when I try to get the length of req.online I get an error as it has a null value.

With the below code I expect req.online.length to have some value, instead it is always null and thus throws an error.

The code in this paste DOES work (req.online.length will equal, say, 2): http://pastebin.com/w4ALpFiT

The code in this paste NOT work (req.online.length is null, throws error trying to check length) : http://pastebin.com/r70juDZP

When I check via the redis cli using:

ZREVRANGEBYSCORE online +inf -inf

I can see the various user-agent values stored as expected.

What do I need to do to get this value back from redis and use it?

Upvotes: 1

Views: 82

Answers (1)

Didier Spezia
Didier Spezia

Reputation: 73306

The problem is related to the order of the middleware settings. The order of the app.use calls is relevant. See the following question for more information:

Node.js / Express.js - How does app.router work?

When you have a doubt about the order of execution, it is useful to add some console.log traces in your code at various places to understand the flow.

Here, you call app.use(app.router) before setting your own middleware functions to get the data from Redis. So node.js routes the request before having a chance to call your middleware functions. The consequence is zrevrangebyscore is never called, and req.inline not set, when the get query is processed.

If you define and app.use the middleware functions before calling app.use(app.router), it will work.

Upvotes: 1

Related Questions