node.js 如何在快递服务器内部进行外部 API 调用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/40222563/
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
How to make a external API call inside express server?
提问by enrico_alvarenga
Hello I ve been trying to implement OneSignal API on my dashboard and I wonder if it is possible to make a API external call inside express server.
您好,我一直在尝试在我的仪表板上实现 OneSignal API,我想知道是否可以在快速服务器内进行 API 外部调用。
Here is an example:
下面是一个例子:
var sendNotification = function(data) {
var headers = {
"Content-Type": "application/json; charset=utf-8",
"Authorization": "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjJj"
};
var options = {
host: "onesignal.com",
port: 443,
path: "/api/v1/notifications",
method: "POST",
headers: headers
};
var https = require('https');
var req = https.request(options, function(res) {
res.on('data', function(data) {
console.log("Response:");
console.log(JSON.parse(data));
});
});
req.on('error', function(e) {
console.log("ERROR:");
console.log(e);
});
req.write(JSON.stringify(data));
req.end();
};
Here it is the app route
这是应用程序路线
app.post('/path', function(req, res){
var message = {
app_id: "5eb5a37e-b458-11e3-ac11-000c2940e62c",
contents: {"en": "English Message"},
included_segments: ["All"]
};
sendNotification(message);
});
Thank you!
谢谢!
回答by jfriend00
I wonder if it is possible to make a API external call inside express server.
我想知道是否可以在快速服务器内部进行 API 外部调用。
Sure, you can contact any external server from a node.js app with http.request()like you are showing or one of the higher level modules built on top of that like the request module.
当然,您可以从 node.js 应用程序中联系任何外部服务器,http.request()就像您所展示的那样,或者建立在它之上的更高级别的模块之一,例如request module。
Here's a simple example from the request module home page:
这是请求模块主页上的一个简单示例:
const request = require('request');
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // Show the HTML for the Google homepage.
}
});
Or, using promises:
或者,使用承诺:
const rp = require('request-promise');
rp('http://www.google.com').then(body => {
console.log(body);
}).catch(err => {
console.log(err);
});
EDIT Jan, 2020 - request() module in maintenance mode
编辑 2020 年 1 月 - request() 模块处于维护模式
FYI, the requestmodule and its derivatives like request-promiseare now in maintenance mode and will not be actively developed to add new features. You can read more about the reasoning here. There is a list of alternatives in this tablewith some discussion of each one. I have been using got()myself and it's built from the beginning to use promises and is simple to use.
仅供参考,该request模块及其衍生产品request-promise现在处于维护模式,不会积极开发以添加新功能。您可以在此处阅读有关推理的更多信息。此表中有一系列备选方案,并对每个备选方案进行了一些讨论。我一直在使用got()我自己,它从一开始就使用 Promise 构建,并且易于使用。
回答by GUDDU KUMAR
you can use Axios client as Axios is a Promise based HTTP client for the browser as well as node.js.
你可以使用 Axios 客户端,因为 Axios 是一个基于 Promise 的浏览器和 node.js 的 HTTP 客户端。
Using Promises is a great advantage when dealing with code that requires a more complicated chain of events. Writing asynchronous code can get confusing, and Promises are one of several solutions to this problem.
在处理需要更复杂的事件链的代码时,使用 Promise 是一个很大的优势。编写异步代码可能会令人困惑,而 Promise 是解决此问题的几种解决方案之一。
First install Axios in your application using npm install axios --save
首先使用在您的应用程序中安装 Axios npm install axios --save
and then you can use this code
然后你可以使用这个代码
const axios = require('axios');
axios.get('api-url')
.then(response => {
console.log(response.data.status);
// console.log(response.data);
res.send(response.data.status);
})
.catch(error => {
console.log(error);
});
回答by Kiryamwibo Yenusu
Kindly try out this solution. i used it and it worked for me.
请尝试此解决方案。我用过它,它对我有用。
var Request = require("request");
Request.get("http://httpbin.org/ip", (error, response, body) => {
if(error) {
return console.dir(error);
}
console.dir(JSON.parse(body));
});

