Javascript 使用 Node.js 调用 JSON API
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11826384/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calling a JSON API with Node.js
提问by Sven
I am trying to get the facebook profile picture of the user logged into my application. Facebook's API states that http://graph.facebook.com/517267866/?fields=picture
returns the correct URL as a JSON object.
我正在尝试获取登录到我的应用程序的用户的 Facebook 个人资料图片。Facebook 的 API 声明http://graph.facebook.com/517267866/?fields=picture
将正确的 URL 作为 JSON 对象返回。
I want to get the URL to the picture out of my code. I tried the following but I am missing something here.
我想从我的代码中获取图片的 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);
});
Running this code results in the following:
运行此代码会产生以下结果:
undefined:1
^
SyntaxError: Unexpected token o
at Object.parse (native)
回答by Laurent Perrin
The res
argument in the http.get()
callback is not the body, but rather an http.ClientResponseobject. You need to assemble the body:
回调中的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);
});
回答by rsp
Problems with other answers:
其他答案的问题:
- unsafe
JSON.parse
- no response code checking
- 不安全
JSON.parse
- 没有响应代码检查
All of the answers here use JSON.parse()
in an unsafe way.
You should always put all calls to JSON.parse()
in a try/catch
block especiallywhen you parse JSON coming from an external source, like you do here.
这里的所有答案都JSON.parse()
以不安全的方式使用。您应该始终将所有调用JSON.parse()
放在一个try/catch
块中,尤其是当您解析来自外部源的 JSON 时,就像您在这里所做的那样。
You can use request
to parse the JSON automatically which wasn't mentioned here in other answers. There is already an answer using request
module but it uses JSON.parse()
to manually parse JSON - which should alwaysbe run inside a try {} catch {}
block to handle errors of incorrect JSON or otherwise the entire app will crash. And incorrect JSON happens, trust me.
您可以使用request
自动解析其他答案中未提及的 JSON。已经有一个使用request
模块的答案,但它用于JSON.parse()
手动解析 JSON - 应始终在try {} catch {}
块内运行以处理不正确的 JSON 错误,否则整个应用程序将崩溃。并且会发生不正确的 JSON,相信我。
Other answers that use http
also use JSON.parse()
without checking for exceptions that can happen and crash your application.
使用的其他答案http
也使用JSON.parse()
而不检查可能发生的异常并使您的应用程序崩溃。
Below I'll show few ways to handle it safely.
下面我将展示几种安全处理它的方法。
All examples use a public GitHub API so everyone can try that code safely.
所有示例都使用公共 GitHub API,因此每个人都可以安全地尝试该代码。
Example with request
示例与 request
Here's a working example with request
that automatically parses JSON:
这是一个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);
}
});
Example with http
and try/catch
用实施例http
和try/catch
This uses https
- just change https
to http
if you want HTTP connections:
这使用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);
});
Example with http
and tryjson
用实施例http
和tryjson
This example is similar to the above but uses the tryjson
module. (Disclaimer: I am the author of that module.)
此示例与上述示例类似,但使用了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);
});
Summary
概括
The example that uses request
is the simplest. But if for some reason you don't want to use it then remember to always check the response code and to parse JSON safely.
使用的例子request
是最简单的。但是如果由于某种原因您不想使用它,那么请记住始终检查响应代码并安全地解析 JSON。
回答by Micha? Per?akowski
I think that for simple HTTP requests like this it's better to use the request
module. You need to install it with npm (npm install request
) and then your code can look like this:
我认为对于像这样的简单 HTTP 请求,最好使用request
module。您需要使用 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)
}
})
回答by MrMins
I'm using get-jsonvery simple to use:
我使用的get-json使用起来非常简单:
$ npm install get-json --save
Import get-json
进口 get-json
var getJSON = require('get-json')
To do a GET
request you would do something like:
要执行GET
请求,您可以执行以下操作:
getJSON('http://api.listenparadise.org', function(error, response){
console.log(response);
})
回答by Washington Guedes
Another solution is to user axios:
另一种解决方案是用户axios:
npm install axios
Code will be like:
代码将如下所示:
const url = `${this.env.someMicroservice.address}/v1/my-end-point`;
const { data } = await axios.get<MyInterface>(url, {
auth: {
username: this.env.auth.user,
password: this.env.auth.pass
}
});
return data;
回答by Micha? Per?akowski
Unirest librarysimplifies this a lot. If you want to use it, you have to install unirest
npm package. Then your code could look like this:
Unirest 库大大简化了这一点。如果你想使用它,你必须安装unirest
npm 包。那么您的代码可能如下所示:
unirest.get("http://graph.facebook.com/517267866/?fields=picture")
.send()
.end(response=> {
if (response.ok) {
console.log("Got a response: ", response.body.picture)
} else {
console.log("Got an error: ", response.error)
}
})