nodejs express redirect to url code example

Example 1: express redirect to url

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

Example 2: express redirect

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

Example 3: express url redirect

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

// The `res.redirect()` function sends back an HTTP 302 by default.
// When an HTTP client receives a response with status 302, it will send
// an HTTP request to the URL in the response, in this case `/to`
app.get('/from', (req, res) => {
  res.redirect('/to');
});
app.get('/to', (req, res) => res.send('Hello, World!'));

Example 4: express js redirect to url

app.all('/secret', function (req, res, next) {
  console.log('Accessing the secret section ...')
  next() // pass control to the next handler
})

Example 5: express js redirect to url

// GET method route
app.get('/', function (req, res) {
  res.send('GET request to the homepage')
})

// POST method route
app.post('/', function (req, res) {
  res.send('POST request to the homepage')
})

Tags:

Html Example