node.js - res.redirect creating another request on the same route -


this first time here, hope post correctly.

i working loopback here, , having problem when try redirect route. have 2 middlewares. first, checks firebase if user if authenticated , allowed visit /dashboard. if no, call next() middleware , 1 redirects /login again.

dashboard.js:

'use strict';     const firebase = require("firebase");     exports.dashboard = (req, res, next) => {       firebase.auth().onauthstatechanged((user) => {           if (user) {             console.log("before render: "+res.headerssent); // false             res.render("dashboard", {photourl: user.photourl, displayname: user.displayname, email: user.email });             console.log("after render: "+res.headerssent);           } else {             // console.log("on else"  );             next()           }       });      };      exports.notlogged = (req, res) => {       console.log("no 1 logged in");       res.redirect('/login');     }; 

route on server.js:

 app.get('/dashboard', dashboard.dashboard, dashboard.notlogged); 

the middleware on login.js:

exports.login = (req, res) => res.render("login") 

and route:

app.get('/login', login.login); 

for example, if try access "/dashboard" , not logged, "console.log("no 1 logged in"); " twice on console, or other log on flow. looks request made, can't understand why or how. if remove redirect , end response or render page, problem not occur.

thank you! :)

update
hi guys! here , still no solution. driving me crazy! hoping comes , tell me wrong! :(

double happening after res.redirect :(

thank again.

you might used middleware in wrong way.

 app.get('/dashboard', dashboard.dashboard, dashboard.notlogged); 

this line means after running dashboard.dashboard, dashboard.notlogged running anyway, whether or not calling next()

so can solve problem this:

     if (user) {         console.log("before render: "+res.headerssent); // false         res.render("dashboard", {photourl: user.photourl, displayname: user.displayname, email: user.email });         console.log("after render: "+res.headerssent);       } else {         // console.log("on else"  );         notlogged()       } 

and remove notlogged here:

 app.get('/dashboard', dashboard.dashboard) 

http://expressjs.com/en/4x/api.html#router


Comments

Popular posts from this blog

amazon web services - S3 Pre-signed POST validate file type? -

c# - Check Keyboard Input Winforms -