How to check HOST using ExpressJS?

I need to check the HOSThttp request, if it is equal to, example.comor www.example.com, I need to perform 301 redirects.

How to do this using Node.js and Express Web Framework?

+5
source share
4 answers

req.header('host')

Use this in request handlers.

+3
source

req.headers.host;

req.header('host');

. , localhost:3000

+3

, , :

if ( req.headers.host.search(/^www/) !== -1 ) {
  res.redirect(301, "http://example.com/");
}

The search method takes a regular expression as the first argument, denoted by surrounding slashes. The first character, ^, in the expression means to explicitly see the beginning of the line. The rest of the expression searches for three explicit w. If the line starts with "www", then the search method returns a match index if it is (0) or -1 if it was not found.

+2
source

All Articles