您好,我一直在尝试在我的仪表板上实现 OneSignal API,我想知道是否可以在 Express 服务器内进行 API 外部调用。
这是一个例子:
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();
};
这里是应用路径
app.post('/path', function(req, res){
var message = {
app_id: "5eb5a37e-b458-11e3-ac11-000c2940e62c",
contents: {"en": "English Message"},
included_segments: ["All"]
};
sendNotification(message);
});
谢谢!
最佳答案
I wonder if it is possible to make a API external call inside express server.
当然,您可以使用 http.request()
从 node.js 应用程序联系任何外部服务器,就像您正在展示的那样,或者像 request module 这样构建在此之上的更高级别的模块之一。
这是请求模块主页的一个简单示例:
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.
}
});
或者,使用 promise :
const rp = require('request-promise');
rp('http://www.google.com').then(body => {
console.log(body);
}).catch(err => {
console.log(err);
});
2020 年 1 月编辑 - request() 模块处于维护模式
仅供引用,request
模块及其衍生模块(如 request-promise
)现在处于维护模式,不会积极开发以添加新功能。您可以阅读更多关于推理 here 的信息。在 this table 中有一个备选方案列表,并对每个备选方案进行了一些讨论。我自己一直在使用 got()
,它从一开始就是使用 Promise 构建的,而且使用简单。
关于node.js - 如何在 express 服务器内进行外部 API 调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40222563/