2016-06-12 95 views
0

我似乎無法得到一個簡單的http請求來處理node.js.以下代碼只是簡單地掛起而不記錄任何內容或打印任何錯誤。使用node.js http模塊

http = require 'http' 

callback = (response) -> 
    console.log 'callback' 
    str = '' 

    # another chunk of data has been recieved, so append it to `str` 
    response.on 'data', (chunk) -> 
    console.log 'data' 
    str += chunk 

    # the whole response has been recieved, so we just print it out here 
    response.on 'end', -> 
    console.log str 

http.get 'http://hacker-news.firebaseio.com/v0/topstories.json', callback 

生成的JavaScript:

// Generated by CoffeeScript 1.10.0 
(function() { 
    var callback, http; 

    http = require('http'); 

    callback = function(response) { 
    var str; 
    console.log('callback'); 
    str = ''; 
    response.on('data', function(chunk) { 
     console.log('data'); 
     return str += chunk; 
    }); 
    return response.on('end', function() { 
     return console.log(str); 
    }); 
    }; 

    http.get('http://hacker-news.firebaseio.com/v0/topstories.json', callback); 

}).call(this); 

回答

0

你現有的代碼似乎好工作的其他網址。特別是這個URL似乎不能通過HTTP,至少在我使用curl時會掛起。在瀏覽器中加載它似乎會返回一個307重定向到HTTPS版本,所以我不確定它爲什麼不響應curl或您的代碼。

無論如何,你可能仍要使用HTTPS URL,因此只需改變你的代碼,這樣做是:

https = require 'https' 

callback = (response) -> 
    console.log 'callback' 
    str = '' 

    # another chunk of data has been recieved, so append it to `str` 
    response.on 'data', (chunk) -> 
    console.log 'data' 
    str += chunk 

    # the whole response has been recieved, so we just print it out here 
    response.on 'end', -> 
    console.log str 

https.get 'https://hacker-news.firebaseio.com/v0/topstories.json', callback 
0

嘗試使用LIB同時支持HTTP和HTTPS一樣,「要求」或「要求-諾言'。

下面的例子做工精細,

var request = require('request'); 
request('https://www.xxxxx.com', function (error, response, body) { 
    if (!error && response.statusCode == 200) { 
    console.log(body); 
    } 
}) 

的更多信息:https://www.npmjs.com/package/request