Sub domains in nodejs

爷,独闯天下 提交于 2020-01-03 10:18:44

问题


How can I handle subdomains request by nodejs?

for example the following code echo test in console for any request on http://localhost:9876/[anything] :

var http = require('http');

http.createServer(function(req, res){
    console.log("test");
}).listen(9876);

now I wanna answer any request on http://[anything].localhost:9876/[anything] it can be done by htaccess in apache,what is alternative in NodeJS?


回答1:


Your application is already capable of handling requests for multiple hosts.

Since you haven't specified a hostname:

[...] the server will accept connections directed to any IPv4 address (INADDR_ANY).

And, you can determine which host was used to make the request from the headers:

var host = req.headers.host; // "sub.domain:9876", etc.

Though, you'll also need to configured an IP address for the subdomains in DNS or hosts.

Or, with a services such as xip.io -- using an IP address rather than localhost:

http://127.0.0.1.xip.io:9876/
http://foo.127.0.0.1.xip.io:9876/
http://anything.127.0.0.1.xip.io:9876/


来源:https://stackoverflow.com/questions/13208145/sub-domains-in-nodejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!