2016-03-23 50 views
2

我正在寫節點和laravel的應用程序。我正在運行小型laravel本地服務器,它解析爲http://localhost:8000。我也在localhost:3000上運行節點服務器。然後嘗試從第二個服務器調用第一個服務器。下面是的NodeJS代碼:如何從localhost(laravel,nodejs)調用localhost?

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) 

我該怎麼做?

回答

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}`); 
}); 
相關問題