使用node.js http模块
问题描述:
我似乎无法得到一个简单的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);
答
你现有的代码似乎好工作的其他网址。特别是这个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
答
尝试使用LIB同时支持HTTP和HTTPS一样,“要求”或“要求-诺言'。
下面的例子做工精细,
var request = require('request');
request('https://www.xxxxx.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
})