Categories
Express JavaScript Answers

How to Redirect in Express.js While Passing Some Data to the Destination?

Spread the love

To redirect in Express.js while passing some data to the destination, we can pass cookies from the originating route to the destination route.

For instance, we can write:

const express = require('express')
const app = express()
const port = 3000
const cookieParser = require("cookie-parser");

app.use(cookieParser());

app.get("/", (req, res) => {
  const context = req.cookies["context"];
  res.clearCookie("context", { httpOnly: true });
  res.send(context);
});

app.get("/category", (req, res) => {
  res.cookie("context", "foo", { httpOnly: true });
  res.redirect("/");
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

We have the /category route which sets the context cookie with the res.cookie method.

'context' is the key, 'foo' is the value. httpOnly sends the cookie via HTTP only.

We redirect with the res.redirect method.

The / route is the desination route.

We get the cookie with req.cookies with the 'context' key.

Then we call res.clearCookie with the 'context' key to clear that cookie.

And then we call res.send with context to return the cookie value as the response.

Therefore, when we go to the /category route, we should be redirected to the / route, which returns foo as the response.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.