I have a register form on every page of my website. During registration some error may occur. After catching the error, I have to return the user to the previous page, showing some error message. The problem is that I do not know from which page the user performed the registration, so I use res.redirect('back');
. However, I cannot just redirect user back, I have to display the error message also, so I have to pass some argument. But res.redirect('back', (reg_error:'username')})
cannot be used directly because res.redirect()
does not support parameters. How can I render the previous page with some parameter?
The res. redirect() function lets you redirect the user to a different URL by sending an HTTP response with status 302. The HTTP client (browser, Axios, etc.) will then "follow" the redirect and send an HTTP request to the new URL as shown below. const app = require('express')(); // The `res.
redirect() function, we can now discuss how to redirect back to original URL in NodeJS. Back redirect: We can use this method to redirects the request back to the referrer. If no referrer is present, the request is redirected to “/” route by default.
session. user = o; res. redirect('/home'); } else{ res. render('/login', { title: 'Hello - Please Login To Your Account' }); } }); } });
You have to store in session. app. get('/url1', function(req, res){ res. send('ok') req.
Using the referer header to find what page your user came from might be helpful:
app.get('/mobileon', function(req, res){
backURL=req.header('Referer') || '/';
// do your thang
res.redirect(backURL);
});
You might also want to store backURL
in req.session, if you need it to persist across multiple routes. Remember to test for the existence of that variable, something like: res.redirect(req.session.backURL || '/')
edit: Since my answer has been getting some upvotes I typed up my current way to do this. It got a little long so you can view it at https://gist.github.com/therealplato/7997908 .
The most important difference is using an explicit 'bounce' parameter in the query string that overrides the Referer url.
A really easy way of implementing this is to use connect-flash, a middleware for express that leverages the session middleware built into express to pass 'flash' messages to the next request.
It means you don't need to add fields to track urls or messages to the form or route patterns for your views.
It provides a simple version of the same feature in Ruby on Rails.
(obviously you have to be using the Express framework for this to use, but I highly recommend that too!)
Plug it in like this:
var flash = require('connect-flash');
var app = express();
app.configure(function() {
app.use(express.cookieParser('keyboard cat'));
app.use(express.session({ cookie: { maxAge: 60000 }}));
app.use(flash());
});
And then use it like this:
app.get('/flash', function(req, res){
req.flash('info', 'Flashed message')
res.redirect('/');
});
app.get('/', function(req, res){
res.render('index', { message: req.flash('info') });
});
If you're using sessions, you can just add that reg_error
object to the req.session
object before your redirect. Then it will be available on the req.session
object when you're loading the previous page.
You could simply have it redirect as res.redirect('..?error=1')
the ?
tag tells the browser that it is a set of optional parameters and the ..
is just a pathname relative recall (like calling cd ..
on terminal to move back one directory)
and your browser will direct to the appropriate page with that tag at the end: http://.....?error=1
then you can simply pull the error on the appropriate page by doing a:
if (req.param("error" == 1)) {
// do stuff bassed off that error match
};
you can hardcode in several different error values and have it respond appropriately depending on what error occurred
Note that this makes your webpage susceptible to manipulation since users can type in their own parameters and get your page to respond to it, so make sure the action you take is not something you wouldn't want people abusing. (Should be fine for simple error displaying)
Use a middleware before before handling requests and put a success and error variable with res object.
take reference below:-
// set local variables middleware
app.use(function(req, res, next) {
res.locals.currentUser = req.user;
// set success flash message
res.locals.success = req.session.success || '';
delete req.session.success;
// set error flash message
res.locals.error = req.session.error || '';
delete req.session.error;
// continue on to next function in middleware chain
next();
});
on encountering the error, use another middleware to handle error and add error with req object.
app.use(function(err, req, res, next) {
console.log(err);
req.session.error = err.message;
res.redirect('back');
});
this will redirect to the previous page along with a error message in res object
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With