Linda
Linda

Reputation: 147

How to redirect requests sent to an external resource in express?

I am trying Express redirects on a website running from localhost. Express captures the http calls made and redirects them as required using the express routing feature. It matches the uri pattern of the requests made from the internal host.

var express = require('express')
var app = express()
app.get('/about', function (req, res) {
  res.send('about')
})

If I am running from localhost:4200, the above code will route requests that resemble, http://localhost:4200/about.

Now let's say there is a button which on click opens https://google.com. Is there a way in express to catch this request and route it elsewhere?

Upvotes: 1

Views: 235

Answers (1)

Thomas Aumaitre
Thomas Aumaitre

Reputation: 807

var express = require('express')
var app = express()
app.get('/about', function (req, res) {
  res.status(301).redirect('https://www.google.com') // status 301 or 302 for permanent or temporary redirection
})

or

app.use((req, res, next) => {
    if (true) { // make your own condition in the express middleware
      return res.status(301).redirect(`https://www.google.com`);
    }
  return next();
});

Upvotes: 1

Related Questions