Reputation: 137
I am trying to implement a Post-Redirect-Get design pattern into my code, which uses Express. What I have is:
var sessionVariable;
app.post('/user', function(req, res) {
sessionVariable = req.session;
// Sets a session variable to a token
sessionVariable.token = req.body.token;
// Redirect to /user
return res.redirect('/user')
});
app.get('/user', function(req, res) {
sessionVariable = req.session;
if(sessionVariable.token){
res.send('Logged in');
} else {
res.send('Not logged in');
}
});
What I expect to happen is when the user submits a POST request to /user, it will define sessionVarlable.token
, then redirect to /user again where it checks if a token exists.
What ends up happening is I will submit the POST request, and through console loggging I can see that app.post fires, but it does not re-direct. Instead, it seems to get stuck on the page where the POST request was omitted.
What is the reason for this?
Edit: Any res
will not fire under app.post, e.g. res.send('test')
doesn't work.
Upvotes: 0
Views: 3121
Reputation: 573
I have posted this answer elsewhere: Understanding the "post/redirect/get" pattern
but here is the code that works for me:
app.post('/data', function(req, res) {
data = req.body;
res.redirect('/db.html');
});
Upvotes: 1
Reputation: 309
Based on the info from the comments, you're making an AJAX request. Instead of making the client redirect from server-side, just do it client-side. Here's an example using Axios on the browser (you can do essentially the same thing with AJAX, just messier):
axios.post('/user', { token: 'tokenhere'}).then(function(response) {
// Status 200 means OK
if (response.status === 200) {
window.location.href = 'user'
}
})
Upvotes: 0