dail
dail

Reputation: 207

How to check the HOST using ExpressJS?

I have to check the HOST of the http request, if it's equal to example.com or www.example.com, I have to do a 301 redirect.

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

Upvotes: 16

Views: 32874

Answers (5)

pguardiario
pguardiario

Reputation: 55002

Today for me it's req.host, req.hostname and req.headers.host - I'm going with req.host though. update vscode tells me req.host is deprecated and use req.hostname instead

Upvotes: 1

Ariful Haque
Ariful Haque

Reputation: 3750

Use

req.headers.host;

or

req.header('host');

Both will return you host name. e.g localhost:3000

Upvotes: 19

Roustalski
Roustalski

Reputation: 156

Do a string search, using a regular expression, as so:

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

The search method accepts a regular expression as the first argument, denoted by surrounding slashes. The first character, ^, in the expression means to explicitly look at the beginning of the string. The rest of the expression is looking for three explicit w's. If the string begins with "www", then the search method will return the index of match, if any (0), or -1, if it wasn't found.

Upvotes: 2

Andz
Andz

Reputation: 2258

req.header('host')

Use that in your request handlers.

Upvotes: 5

Related Questions