admin管理员组文章数量:1167180
I have to check the HOST
of the http request, if it's equal to example
or www.example
, I have to do a 301 redirect.
How can I do this using Node.js and Express Web Framework?
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?
Share Improve this question edited Jun 29, 2011 at 17:10 MPelletier 16.6k18 gold badges89 silver badges140 bronze badges asked Jun 28, 2011 at 7:55 daildail 2071 gold badge2 silver badges5 bronze badges 2- 5 The HOST of an http request is part of the header. The request object passed to your callback has a .header() method. Did you try reading the documentation at all? – Karl Knechtel Commented Jun 28, 2011 at 8:00
- Does this answer your question? Get hostname of current request in node.js Express – Jason Commented Apr 27, 2024 at 20:27
5 Answers
Reset to default 19Use
req.headers.host;
or
req.header('host');
Both will return you host name. e.g localhost:3000
req.header('host')
Use that in your request handlers.
Express.js guide - request.hostname
Express.js guide - request.redirect
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.
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
本文标签: javascriptHow to check the HOST using ExpressJSStack Overflow
版权声明:本文标题:javascript - How to check the HOST using ExpressJS? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1737642086a2000070.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论