Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I redirect in expressjs while passing some context?

I am using express to make a web app in node.js. This is a simplification of what I have:

var express = require('express'); var jade = require('jade'); var http = require("http");   var app = express(); var server = http.createServer(app);  app.get('/', function(req, res) {     // Prepare the context     res.render('home.jade', context); });  app.post('/category', function(req, res) {     // Process the data received in req.body     res.redirect('/'); }); 

My problem is the following:

If I find that the data sent in /category doesn't validate, I would like pass some additional context to the / page. How could I do this? Redirect doesn't seem to allow any kind of extra parameter.

like image 732
Enrique Moreno Tent Avatar asked Sep 26 '13 18:09

Enrique Moreno Tent


People also ask

How do I redirect in Express?

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.

Can we send data in redirect?

Yes. If not passing the object, then passing the id so that the other function can retrieve it from the database.

What does res redirect do in NodeJS?

The res. redirect() function redirects to the URL derived from the specified path, with specified status, a integer (positive) which corresponds to an HTTP status code.

How do I redirect a path in node JS?

nodejs1min read In express, we can use the res. redirect() method to redirect a user to the different route. The res. redirect() method takes the path as an argument and redirects the user to that specified path.


1 Answers

There are a few ways of passing data around to different routes. The most correct answer is, of course, query strings. You'll need to ensure that the values are properly encodeURIComponent and decodeURIComponent.

app.get('/category', function(req, res) {   var string = encodeURIComponent('something that would break');   res.redirect('/?valid=' + string); }); 

You can snag that in your other route by getting the parameters sent by using req.query.

app.get('/', function(req, res) {   var passedVariable = req.query.valid;   // Do something with variable }); 

For more dynamic way you can use the url core module to generate the query string for you:

const url = require('url');     app.get('/category', function(req, res) {     res.redirect(url.format({        pathname:"/",        query: {           "a": 1,           "b": 2,           "valid":"your string here"         }      }));  }); 

So if you want to redirect all req query string variables you can simply do

res.redirect(url.format({        pathname:"/",        query:req.query,      });  }); 

And if you are using Node >= 7.x you can also use the querystring core module

const querystring = require('querystring');     app.get('/category', function(req, res) {       const query = querystring.stringify({           "a": 1,           "b": 2,           "valid":"your string here"       });       res.redirect('/?' + query);  }); 

Another way of doing it is by setting something up in the session. You can read how to set it up here, but to set and access variables is something like this:

app.get('/category', function(req, res) {   req.session.valid = true;   res.redirect('/'); }); 

And later on after the redirect...

app.get('/', function(req, res) {   var passedVariable = req.session.valid;   req.session.valid = null; // resets session variable   // Do something }); 

There is also the option of using an old feature of Express, req.flash. Doing so in newer versions of Express will require you to use another library. Essentially it allows you to set up variables that will show up and reset the next time you go to a page. It's handy for showing errors to users, but again it's been removed by default. EDIT: Found a library that adds this functionality.

Hopefully that will give you a general idea how to pass information around in an Express application.

like image 101
AlbertEngelB Avatar answered Oct 10 '22 16:10

AlbertEngelB