如何从localhost(laravel,nodejs)调用localhost?

时间:2016-03-23 22:05:28

标签: php node.js laravel networking localhost

我正在编写一个带有node和laravel的应用程序。我正在运行小型laravel本地服务器,它解析为http://localhost:8000。我也在localhost:3000上运行节点服务器。然后尝试从第二个服务器调用第一个服务器。这是NodeJs代码:

var restify = require('restify');

var server = restify.createServer();

server.listen(3000, function() {
  console.log('%s listening at %s', server.name, server.url);
});

这是我发出http请求的地方:

var http = require('http');


module.exports = {
    call: function (host, path) {
        var options = {
          host: host,
          path: path,
          port: 8000,
          method: 'GET'
        };

        callback = function(response) {
          var str = '';

          response.on('data', function (chunk) {
            str += chunk;
          });

          response.on('end', function () {
            return str;
          });
        }

        http.request(options, callback).end();
    }
}

这是我正在进行的实际通话:

httpCaller.call('http://localhost', '/fire');

我在命令行上得到以下响应:

Error: getaddrinfo ENOTFOUND http://localhost http://localhost:8000
    at errnoException (dns.js:26:10)
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:77:26)

我尝试删除http://并只调用本地主机,并获得以下内容:

Error: connect ECONNREFUSED 127.0.0.1:8000
    at Object.exports._errnoException (util.js:890:11)
    at exports._exceptionWithHostPort (util.js:913:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1057:14)

我该怎么做?

1 个答案:

答案 0 :(得分:0)

尝试使用http.get功能?

http.get('http://localhost:8000/fire', (res) => {
  console.log(`Got response: ${res.statusCode}`);
  // consume response body
  res.resume();
}).on('error', (e) => {
  console.log(`Got error: ${e.message}`);
});