nodejs express redirect code example

Example 1: javascript redirect

window.location.href = "http://mywebsite.com/home.html";

Example 2: express redirect to url

app.get('/', (req, res) => {
  res.redirect('/about');
})

Example 3: express redirect

app.get('/', (req, res) => {
  res.redirect('/foo/bar');
});

Example 4: express redirect

res.redirect('https://google.com')

Example 5: express request path

// GET 'http://www.example.com/admin/new?a=b'
app.get('/admin', (req, res, next) => {
  req.originalUrl; // '/admin/new?a=b' (full path with query string)
  req.baseUrl; // '/admin'
  req.path; // '/new'
  req.baseUrl + req.path; // '/admin/new' (full path without query string)
});

Example 6: express redirect

res.redirect('/foo/bar')
res.redirect('http://example.com')
res.redirect(301, 'http://example.com')
res.redirect('../login')

Tags:

Misc Example