lib/application: improve URL building algo

When running on Unix and no hostname is specified, use `0.0.0.0`
as the hostname instead of `localhost`.

When running on Windows and the hostname is either not specified or
it is `0.0.0.0` or `::`, use `localhost` in the URL. The reason is
that Windows cannot open URLs using `0.0.0.0` as a hostname.
This commit is contained in:
Miroslav Bajtoš 2014-10-17 09:58:02 +02:00
parent f511bd38c9
commit 80020eb273
3 changed files with 23 additions and 7 deletions

View File

@ -435,10 +435,24 @@ app.listen = function(cb) {
server.on('listening', function() {
self.set('port', this.address().port);
var listeningOnAll = false;
var host = self.get('host');
if (!host) {
listeningOnAll = true;
host = this.address().address;
self.set('host', host);
} else if (host === '0.0.0.0' || host === '::') {
listeningOnAll = true;
}
if (!self.get('url')) {
// A better default host would be `0.0.0.0`,
// but such URL is not supported by Windows
var host = self.get('host') || '127.0.0.1';
if (process.platform === 'win32' && listeningOnAll) {
// Windows browsers don't support `0.0.0.0` host in the URL
// We are replacing it with localhost to build a URL
// that can be copied and pasted into the browser.
host = 'localhost';
}
var url = 'http://' + host + ':' + self.get('port') + '/';
self.set('url', url);
}

View File

@ -213,8 +213,9 @@ describe('app', function() {
app.set('host', undefined);
app.listen(function() {
expect(app.get('url'), 'url')
.to.equal('http://127.0.0.1:' + app.get('port') + '/');
var host = process.platform === 'win32' ? 'localhost' : app.get('host');
var expectedUrl = 'http://' + host + ':' + app.get('port') + '/';
expect(app.get('url'), 'url').to.equal(expectedUrl);
done();
});
});

View File

@ -12,7 +12,7 @@ describe('RemoteConnector', function() {
remoteApp.use(loopback.rest());
remoteApp.listen(0, function() {
test.dataSource = loopback.createDataSource({
host: remoteApp.get('host'),
host: 'localhost',
port: remoteApp.get('port'),
connector: loopback.Remote
});
@ -38,7 +38,7 @@ describe('RemoteConnector', function() {
remoteApp.listen(0, function() {
test.remote = loopback.createDataSource({
host: remoteApp.get('host'),
host: 'localhost',
port: remoteApp.get('port'),
connector: loopback.Remote
});
@ -63,6 +63,7 @@ describe('RemoteConnector', function() {
var m = new RemoteModel({foo: 'bar'});
m.save(function(err, inst) {
if (err) return done(err);
assert(inst instanceof RemoteModel);
assert(calledServerCreate);
done();