Lahiru Udayanga
Lahiru Udayanga

Reputation: 369

How to pass data from one route to another nodejs with expressjs

I want to add a certain attribute to the request object and access the added it from another route after redirecting. The following code shows what I exactly need.

const express = require('express')
const app = express()

app.get('/test1',(req,res)=>{
console.log('test1')
req.name = 'lahiru'
res.redirect('/test2')
})

app.get('/test2',(req,res)=>{
console.log('test2')
let val = req.name
console.log(val)
})

app.listen(3000)

But when I sends a request to the '/test1', I get the following output.

test1
test2
undefined

I tried this with express-session, but log-returns the same 'undefined'. Can anyone please help. Thanks in advance.

Upvotes: 3

Views: 6623

Answers (2)

Julian Schlickmann
Julian Schlickmann

Reputation: 199

you could use the first route as a middleware to modify the req param.

const express = require("express");
const app = express();

const middleware = (req, res, next) => {
  console.log("test1");
  req.name = "lahiru";
  next();
};

app.get("/test2", middleware, (req, res) => {
   console.log("test2");
   let val = req.name;
   console.log(val);
});

app.listen(3000);

Upvotes: 4

Marcos Casagrande
Marcos Casagrande

Reputation: 40414

You can do one of the following if you want name available in /test2:

  • Pass the data in the URL using querystring: /test2?name={name}
  • Change the route to: /test2/:name
  • Use cookies
  • Other type of session
app.get('/test1',(req,res)=>{
    const name = 'lahiru'
    res.redirect(`/test2/${name}`)
    // res.redirect(`/test2/?name=${name}`)
})

// using req.params
app.get('/test2/:name',(req,res)=>{
    let val = req.params.name
    console.log(val)
})
// using query string
app.get('/test2',(req,res)=>{
    let val = req.query.name
    console.log(val)
})

Upvotes: 5

Related Questions