Linux 如何使用 ExpressJS 检查 HOST?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6503331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 04:47:33  来源:igfitidea点击:

How to check the HOST using ExpressJS?

javascriptlinuxnode.jsexpress

提问by dail

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

我必须检查HOSThttp 请求的 ,如果它等于example.comwww.example.com,我必须进行 301 重定向。

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

我如何使用 Node.js 和 Express Web Framework 做到这一点?

回答by Andz

req.header('host')

req.header('host')

Use that in your request handlers.

在您的请求处理程序中使用它。

回答by Roustalski

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.

search 方法接受一个正则表达式作为第一个参数,用斜杠表示。表达式中的第一个字符 ^ 表示显式查看字符串的开头。表达式的其余部分正在寻找三个显式 w。如果字符串以“www”开头,则搜索方法将返回匹配项的索引(如果有)(0)或 -1(如果未找到)。

回答by Ariful Haque

Use

req.headers.host;

or

或者

req.header('host');

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

两者都会返回您的主机名。例如localhost:3000

回答by pguardiario

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

今天对我来说是 req.host、req.hostname 和 req.headers.host——不过我要使用 req.host。