使用 nodeJS 访问 imgur API - 参数在 AJAX 中有效,但在 nodeJS 中无效
Accessing the imgur API with nodeJS - parameters work in AJAX, but not in nodeJS
努力让 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');
}
});
它returns错误信息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 的经验吗?我错过了什么?
看看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();
努力让 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');
}
});
它returns错误信息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 的经验吗?我错过了什么?
看看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();