【问题标题】:Using node.js http module使用 node.js http 模块
【发布时间】:2016-06-13 13:15:17
【问题描述】:

我似乎无法获得使用 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);

【问题讨论】:

    标签: node.js http coffeescript


    【解决方案1】:

    您现有的代码似乎可以与其他 URL 一起正常工作。特别是该 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
    

    【讨论】:

      【解决方案2】:

      尝试使用同时支持 http 和 https 的库,例如“request”或“request-promise”。

      下面的例子运行良好,

      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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-04-14
        • 2018-01-05
        • 2012-01-17
        • 2016-03-18
        • 1970-01-01
        • 2018-07-02
        • 1970-01-01
        相关资源
        最近更新 更多