【问题标题】:Accessing the imgur API with nodeJS - parameters work in AJAX, but not in nodeJS使用 nodeJS 访问 imgur API - 参数在 AJAX 中有效,但在 nodeJS 中无效
【发布时间】:2017-04-25 02:46:46
【问题描述】:

努力让 nodeJS https.request 或 https.get 使用 imgur API(也尝试使用 http 模块)。这是我的 https.request 代码:

var https = require('https')

var imgurAPIOptions = {
    hostname : 'api.imgur.com',
    path: '/3/gallery/search/time/1/?q=cat',
    headers: {'Authorization': 'Client-ID xxxxxxxxxxxx'},
    json: true,
    method: 'GET'
};

https.request(imgurAPIOptions,function(err,imgurResponse){
    if (err) {console.log('ERROR IN IMGUR API ACCESS')

} else {

    console.log('ACCESSED IMGUR API');
}

});

它返回错误消息console.log。

这是使用 jQuery AJAX 的等效客户端请求的(工作)代码:

$(document).ready(function(){

  $.ajax({
      headers: {
    "Authorization": 'Client-ID xxxxxxxxxxxx'
  },
    url: 'https://api.imgur.com/3/gallery/search/time/1/?q=cat',
    success:function(data){
      console.log(data)
    }
  })

});

这里有没有人有让 imgur API 工作的经验?我错过了什么?

【问题讨论】:

  • err的内容是什么?
  • 一个在控制台中被裁剪的该死的伟大对象/数组。给我几分钟,我会试着提取它。
  • 根据docshttps.request回调中的第一个参数是数据,而不是错误。 err 中的对象是 API 响应吗?

标签: ajax node.js api https imgur


【解决方案1】:

看看https docs。您需要进行一些更改:

请求回调中的第一个参数是响应,而不是错误。如果要检查错误,可以在请求上监听error 事件。

一旦请求收到数据,就可以输出了。

var https = require('https');

var options = {
  hostname: 'api.imgur.com',
  path: '/3/gallery/search/time/1/?q=cat',
  headers: {'Authorization': 'Client-ID xxxxxxxxxxxx'},
  method: 'GET'
};

var req = https.request(options, function(res) {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', function(d) {
    process.stdout.write(d);
  });
});

req.on('error', function(e) {
  console.error(e);
});

req.end();

【讨论】:

  • 我确实有 .end();包括,只是忘了把它放在上面的sn-p上。我会用你的语法试一试,看看它是否有效。
  • 是的,行得通。认为我只是被请求所抛弃,不使用“正常”函数(错误,数据)回调结构并使用不熟悉的 API。
  • 没问题。有一个名为request 的包非常流行,并且在某些情况下使用起来更好。该包遵循function(err, data) 模式。
猜你喜欢
  • 2017-06-26
  • 1970-01-01
  • 2016-02-27
  • 2015-05-19
  • 1970-01-01
  • 2016-02-19
  • 2020-02-26
  • 1970-01-01
  • 2023-02-24
相关资源
最近更新 更多