【问题标题】:How to make a external API call inside express server?如何在快递服务器内进行外部 API 调用?
【发布时间】:2017-03-06 11:24:39
【问题描述】:

您好,我一直在尝试在我的仪表板上实现 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);
});

谢谢!

【问题讨论】:

    标签: node.js api express onesignal


    【解决方案1】:

    我想知道是否可以在 express 内部进行 API 外部调用 服务器。

    当然,您可以使用http.request()(如您所展示)或在此基础上构建的更高级别模块之一(如request module)从 node.js 应用程序联系任何外部服务器。

    这是请求模块主页的一个简单示例:

    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. 
      }
    });
    

    或者,使用承诺:

     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)现在处于维护模式,不会积极开发以添加新功能。你可以阅读更多关于推理的信息herethis table 中有一个备选方案列表,其中对每个备选方案进行了一些讨论。我自己一直在使用got(),它从一开始就是使用 Promise 构建的,而且使用简单。

    【讨论】:

      【解决方案2】:

      您可以使用 Axios 客户端,因为 Axios 是基于 Promise 的浏览器以及 node.js 的 HTTP 客户端。

      在处理需要更复杂事件链的代码时,使用 Promises 是一个很大的优势。编写异步代码可能会让人感到困惑,Promises 是解决这个问题的几种解决方案之一。

      首先使用npm install axios --save在你的应用程序中安装Axios

      然后你就可以使用这个代码了

      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);
          });
      

      【讨论】:

        【解决方案3】:

        请尝试此解决方案。我用过它,它对我有用。

        var Request = require("request");
        
        Request.get("http://httpbin.org/ip", (error, response, body) => {
            if(error) {
                return console.dir(error);
            }
            console.dir(JSON.parse(body));
        });

        【讨论】:

          【解决方案4】:

          您可以使用request-promise-native,它使用原生 ES6 承诺。

          安装 request-promise-native 包

          npm install --save request
          npm install --save request-promise-native
          

          如下使用:

          const request = require('request-promise-native');
          
          const options = {
              method: 'GET',
              uri: 'https://www.google.com'
          }
          
          request(options).then(response => {
              console.log(response);
          }, error => {
              console.log(error);
          });
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2021-01-19
            • 2022-01-15
            • 2020-02-17
            • 2016-01-21
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2019-06-25
            相关资源
            最近更新 更多