Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 624
dail Avatar asked Jun 28 '11 07:06

dail


People also ask

How do I find my hostname in Express?

We can use the req. hostname property to get the hostname from a current incoming request in express. Example: const express = require("express"); const app = express(); app.

How do I find the hostname in Node?

To get the name or hostname of the OS, you can use the hostname() method from the os module in Node. js. /* Get hostname of os in Node. js */ // import os module const os = require("os"); // get host name const hostName = os.

What is req host?

The req. hostname contains the hostname that is derived from the host HTTP header. This property will get its value from the X-Forwarded-Host header field when the trust setting properties are enabled (or not set to false). This header can be set by the client or by the proxy.

Who is using Expressjs?

Express. js is used by Fox Sports, PayPal, Uber and IBM.


5 Answers

Express.js guide - request.hostname

Express.js guide - request.redirect

like image 136
Kamil Avatar answered Oct 21 '22 23:10

Kamil


Use

req.headers.host;

or

req.header('host');

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

like image 20
Ariful Haque Avatar answered Oct 21 '22 22:10

Ariful Haque


req.header('host')

Use that in your request handlers.

like image 39
Andz Avatar answered Oct 21 '22 23:10

Andz


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.

like image 25
Roustalski Avatar answered Oct 21 '22 21:10

Roustalski


Today for me it's req.host, req.hostname and req.headers.host - I'm going with req.host though.

like image 42
pguardiario Avatar answered Oct 21 '22 23:10

pguardiario