在 Node.js 中向 JSON API 发出 GET 请求?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25183228/
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
Make a GET request to JSON API in Node.js?
提问by saileshpypatel
Wondering how I can make a GET request to a JSON API using Node.js. I preferably want to use Express however it is not necessary, and for the output to be on a Jade page. I'm still completely new to Node.js and backend languages as a whole.
想知道如何使用 Node.js 向 JSON API 发出 GET 请求。我最好使用 Express 但它不是必需的,并且输出在 Jade 页面上。作为一个整体,我对 Node.js 和后端语言仍然完全陌生。
回答by Sleep Deprived Bulbasaur
var request = require('request');
request('<API Call>', function (error, response, body) {
if (!error && response.statusCode == 200) {
var info = JSON.parse(body)
}
})
This will make an HTTP request to the API and upon success parse the response into JSON.
这将向 API 发出 HTTP 请求,成功后将响应解析为 JSON。
As far as getting the response onto a Jade page do you wish to do an API call (to your own server) and then use AngularJS/ jQuery/ another framework to fill in the information?
至于将响应发送到 Jade 页面,您是否希望进行 API 调用(到您自己的服务器),然后使用 AngularJS/jQuery/另一个框架来填写信息?
If you wish to add this to your own route consider embedding it like such:
如果您希望将此添加到您自己的路线中,请考虑将其嵌入如下:
var express = require('express');
var cors = require('cors');
var request = require('request');
var app = express();
app.use(express.bodyParser());
app.use(cors());
app.get('<Your Route>', function(req, res){
request('<API Call>', function (error, response, body) {
if (!error && response.statusCode == 200) {
var info = JSON.parse(body)
// do more stuff
res.send(info);
}
})
});
app.listen(3000);
console.log("The server is now running on port 3000.");
回答by funerr
I like to use the request package:
我喜欢使用请求包:
npm install --save request
And the code:
和代码:
var request = require('request');
request({url: 'http://yourapi.com/', json: true}, function(err, res, json) {
if (err) {
throw err;
}
console.log(json);
});
回答by Quy
Also, the same people who brought you the requestpackage, have come out with a promise based version backed by bluebird called, not surprisingly, request-promise:
此外,为您带来request软件包的同一个人推出了由 bluebird 支持的基于 Promise 的版本,毫不奇怪,request-promise:
Some folks also prefer super agent, which allows you to chain commands:
有些人还喜欢超级代理,它允许您链接命令:
Here's an example from their docs:
这是他们文档中的一个示例:
request
.post('http://localhost:3000/api/pet')
.send({ name: 'Manny', species: 'cat' })
.set('X-API-Key', 'foobar')
.set('Accept', 'application/json')
.end(function(err, res){
// Calling the end function will send the request
});

