I keep encountering this error when I execute my code which has the pseudocode listed below (To clarify, my code is based on the react-redux-universal-hot-example)
Error: Can't set headers after they are sent.
[2] at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:344:11)
[2] at ServerResponse.header (/pathToUI/ui/node_modules/express/lib/response.js:718:10)
[2] at ServerResponse.location (/pathToUI/ui/node_modules/express/lib/response.js:835:8)
[2] at ServerResponse.redirect (/pathToUI/ui/node_modules/express/lib/response.js:874:8)
[2] at api.js:165:11
[2] at Layer.handle [as handle_request] (/pathToUI/ui/node_modules/express/lib/router/layer.js:95:5)
[2] at trim_prefix (/pathToUI/ui/node_modules/express/lib/router/index.js:312:13)
[2] at /pathToUI/ui/node_modules/express/lib/router/index.js:280:7
[2] at Function.process_params (/pathToUI/ui/node_modules/express/lib/router/index.js:330:12)
[2] at next (/pathToUI/ui/node_modules/express/lib/router/index.js:271:10
I am trying to redirect the user to the homepage (/) and the user is at /home after having logged in. Basically, the session is controlled by a timer in the express session. When the time is up, I want to redirect the user to the homepage (the next time a request is made).
the following code would be in the api.js file
app.use( (req, res, next) => {
if (req.session.user != undefined) {
if(sessionNotOver)
Renew session
}
else if (sessionOver/ expired ) {
console.log('expired session');
res.status(403).end('SESSION EXPIRED');
res.redirect('/');
return;
//req.session.destroy();
} else {
console.log('session has no user, but it is: ' + JSON.stringify(req.session));
}
});
I am able to correctly keep track of the session, but I am having trouble redirecting the user to the homepage. What tips do you have for me to accomplish this? Would it be better for me to put the redirect somewhere else (ie. in server.js?)
I have tried consulting multiple stackoverflow posts and I have also done a lot of Googling/ testing, but nothing seems to work. I might be misunderstanding something though, so it would be nice if someone could clarify some things and / or give me some tips. Thanks!
EDIT So I tried changing the line as Shimon Brandsdorfer mentioned below, but my application still doesn't redirect, now it is just stuck on a loading screen which is another component that displays a loading gif until the other timer (in App.js) times out.