问题
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