我似乎无法获得一个简单的http请求来使用node.js.以下代码只是挂起而不记录任何内容或打印任何错误。
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 :(得分: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
答案 1 :(得分:0)
尝试使用支持http和https的lib,例如'request'或'request-promise'。
以下示例正常,
var request = require('request');
request('https://www.xxxxx.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
})