Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: req.next is not a function [closed]

Getting this error in node, I think it's due to something to do with one of my pieces of middleware, but the line of code that it points to is my user controller at a res.render() call.

I can't find anyone writing about this error online and couldn't figure out the cause after looking at the code for a while. Any ideas?

enter image description here

like image 651
Anthony Avatar asked Sep 13 '17 17:09

Anthony


2 Answers

If you take a look at the Express source code you'll see that line 966 of response.js (from the stack) is this:

if (err) return req.next(err);

The error message you're seeing suggests that req is defined but next is not a function. If you look a bit further up you can see where req is coming from:

var req = this.req;

where this is the response object that you called render on.

While next is usually just passed as an argument to a callback, there is also supposed to be a function called next attached to the request. It isn't something you'd normally interact with yourself, it's part of the inner workings.

So I see two possibilities. Either something has changed res.req to point at the wrong object, or something has blown away req.next. I suggest adding in some console logging to isolate exactly where this goes wrong. For example, if you put this between each of your middleware calls:

app.use(function(req, res, next) {
    console.log(typeof req.next);

    next();
});

it'll allow you to identify the point where req.next switches from being the function it should be to being something else.

like image 127
skirtle Avatar answered Oct 21 '22 06:10

skirtle


In my case, I need to return the next()

// Error
    app.use((req, res, next) => {
      if(!req.session.userId) {
        next(); // <<<<< Error
      } 
    })

// Solution
    app.use((req, res, next) => {
      if(!req.session.userId) {
        return next();
      } 
    })
like image 5
SimplifyJS Avatar answered Oct 21 '22 05:10

SimplifyJS