1

Currently, in a function inside of an Express app I am working on, I would like to make a redirect after gathering some data, have that redirect finish, return that data and then continue from where I left off.

For example:

> res.redirect('my/path' + someVariable);
> Goes through various routes, and web pages, gathering data
> Come back to the point after the initial redirect, with new data
> Do some checks with previous and new data, continue on

Is this something that is common? Are there easy ways of accomplishing this? I can clarify further if need be.

Thanks!

User 5842
  • 2,849
  • 7
  • 33
  • 51
  • 2
    You can add querystring that contains the path to redirect back after finishing gathering the data, and handle this querystring in the redirected handler that eventually redirects back. – Kevin Qian Mar 15 '18 at 20:02
  • @KevinQian you should make that an answer and provide an example if possible? I'd be interested in seeing how it is done as well. – Jordan Mar 15 '18 at 20:03
  • What do you expect to do after you send the `res.redirect()`? That will start a whole new page request which will trigger a new route handler. Your current route handler really has nothing left to do (except maybe clean up after itself) after you do the `res.redirect()`. – jfriend00 Mar 16 '18 at 00:11

1 Answers1

2

Pass data as querystring around. See example below (run locally and navigate to localhost:4000/path0 to see the effect).

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

app.get('/path0', (req, res, next) => {
  if (!req.query.value) { // no data yet
    res.redirect('/path1?redirect=/path0') // go to another path to fetch data
  } else {
    res.write(`<h1>Value is: ${req.query.value}</h1>`)
    res.end()
  }
})

app.get('/path1', (req, res, next) => {
  let value = Math.random(10) // assume this is the data we want
  let redirectPath = req.query.redirect || '/path0'
  res.redirect(`/path0?value=${value}`) // redirect back, this time pass data as part of querystring
})

app.listen(4000)

Another possible way to pass data back is through Set-Cookie after first redirect, instead of directly passing the data into querystring of second redirect. (should be working in most modern browser even given 302, see this)

Kevin Qian
  • 2,532
  • 1
  • 16
  • 26