Sve*_*ven 69 javascript json http node.js
我正在尝试获取登录到我的应用程序的用户的facebook个人资料图片.Facebook的API声明http://graph.facebook.com/517267866/?fields=picture返回正确的URL作为JSON对象.
我想从我的代码中获取图片的URL.我试过以下但我在这里遗漏了一些东西.
var url = 'http://graph.facebook.com/517267866/?fields=picture';
http.get(url, function(res) {
var fbResponse = JSON.parse(res)
console.log("Got response: " + fbResponse.picture);
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
Run Code Online (Sandbox Code Playgroud)
运行此代码会导致以下结果:
undefined:1
^
SyntaxError: Unexpected token o
at Object.parse (native)
Run Code Online (Sandbox Code Playgroud)
Lau*_*rin 132
回调中的res参数http.get()不是正文,而是http.ClientResponse对象.你需要组装身体:
var url = 'http://graph.facebook.com/517267866/?fields=picture';
http.get(url, function(res){
var body = '';
res.on('data', function(chunk){
body += chunk;
});
res.on('end', function(){
var fbResponse = JSON.parse(body);
console.log("Got a response: ", fbResponse.picture);
});
}).on('error', function(e){
console.log("Got an error: ", e);
});
Run Code Online (Sandbox Code Playgroud)
rsp*_*rsp 36
JSON.parse这里的所有答案都JSON.parse()以不安全的方式使用.您应该始终将所有调用JSON.parse()放在一个try/catch块中,尤其是当您解析来自外部源的JSON时,就像您在此处一样.
您可以使用request自动解析JSON,这在其他答案中没有提到.已经有一个使用request模块的答案,但它用于JSON.parse()手动解析JSON - 应始终在try {} catch {}块内运行以处理错误的JSON错误,否则整个应用程序将崩溃.不正确的JSON发生了,相信我.
其他使用的答案http也可以使用JSON.parse()而不检查可能发生的异常并使应用程序崩溃.
下面我将展示一些安全处理它的方法.
所有示例都使用公共GitHub API,因此每个人都可以安全地尝试该代码.
request这是一个request自动解析JSON 的工作示例:
'use strict';
var request = require('request');
var url = 'https://api.github.com/users/rsp';
request.get({
url: url,
json: true,
headers: {'User-Agent': 'request'}
}, (err, res, data) => {
if (err) {
console.log('Error:', err);
} else if (res.statusCode !== 200) {
console.log('Status:', res.statusCode);
} else {
// data is already parsed as JSON:
console.log(data.html_url);
}
});
Run Code Online (Sandbox Code Playgroud)
http和示例try/catch这用https- 如果你想要HTTP连接,只需更改https为http:
'use strict';
var https = require('https');
var options = {
host: 'api.github.com',
path: '/users/rsp',
headers: {'User-Agent': 'request'}
};
https.get(options, function (res) {
var json = '';
res.on('data', function (chunk) {
json += chunk;
});
res.on('end', function () {
if (res.statusCode === 200) {
try {
var data = JSON.parse(json);
// data is available here:
console.log(data.html_url);
} catch (e) {
console.log('Error parsing JSON!');
}
} else {
console.log('Status:', res.statusCode);
}
});
}).on('error', function (err) {
console.log('Error:', err);
});
Run Code Online (Sandbox Code Playgroud)
http和示例tryjson此示例与上述类似,但使用该tryjson模块.(免责声明:我是该模块的作者.)
'use strict';
var https = require('https');
var tryjson = require('tryjson');
var options = {
host: 'api.github.com',
path: '/users/rsp',
headers: {'User-Agent': 'request'}
};
https.get(options, function (res) {
var json = '';
res.on('data', function (chunk) {
json += chunk;
});
res.on('end', function () {
if (res.statusCode === 200) {
var data = tryjson.parse(json);
console.log(data ? data.html_url : 'Error parsing JSON!');
} else {
console.log('Status:', res.statusCode);
}
});
}).on('error', function (err) {
console.log('Error:', err);
});
Run Code Online (Sandbox Code Playgroud)
使用的示例request是最简单的.但如果由于某种原因您不想使用它,请记住始终检查响应代码并安全地解析JSON.
Mic*_*ski 16
我认为对于像这样的简单HTTP请求,最好使用该request模块.您需要使用npm(npm install request)安装它,然后您的代码可能如下所示:
const request = require('request')
,url = 'http://graph.facebook.com/517267866/?fields=picture'
request(url, (error, response, body)=> {
if (!error && response.statusCode === 200) {
const fbResponse = JSON.parse(body)
console.log("Got a response: ", fbResponse.picture)
} else {
console.log("Got an error: ", error, ", status code: ", response.statusCode)
}
})
Run Code Online (Sandbox Code Playgroud)
我正在使用get-json非常简单:
$ npm install get-json --save
Run Code Online (Sandbox Code Playgroud)
进口 get-json
var getJSON = require('get-json')
Run Code Online (Sandbox Code Playgroud)
要发出GET请求,您可以执行以下操作:
getJSON('http://api.listenparadise.org', function(error, response){
console.log(response);
})
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
129664 次 |
| 最近记录: |