【问题标题】:API GET request from my api to another api?从我的 api 到另一个 api 的 API GET 请求?
【发布时间】:2018-12-03 12:39:45
【问题描述】:

我正在尝试创建一个将 GET 请求发送到另一个 API 的后端。

例如:

我的 API:localhost:3000/
路线:/getdata/data1
其他API:api.com/target/data

(这是一个假的 URL,假设这条路由有我想要的数据)

如何从我的 API 向该 API 发送获取请求? Ajax.get?

【问题讨论】:

标签: node.js api express controller routing


【解决方案1】:

可以使用node内置的http模块,也可以使用request等第三方包。

HTTP

一个使用内置http模块的例子例如:

// The 'https' module can also be used
const http = require('http');

// Example route
app.get('/some/api/endpoint',  (req, res) => {

    http.get('http://someapi.com/api/endpoint', (resp) => {
        let data = '';

        // Concatinate each chunk of data
        resp.on('data', (chunk) => {
          data += chunk;
        });

        // Once the response has finished, do something with the result
        resp.on('end', () => {
          res.json(JSON.parse(data));
        });

        // If an error occured, return the error to the user
      }).on("error", (err) => {
        res.json("Error: " + err.message);
      });
});

请求

或者,可以使用第三方包,例如request

首次安装请求:

npm install -s request

然后将您的路线更改为以下内容:

const request = require('request');

// Example route
app.get('/some/api/endpoint',  (req, res) => {

    request('http://someapi.com/api/endpoint',  (error, response, body) => {
        if(error) {
            // If there is an error, tell the user 
            res.send('An erorr occured')
        }
        // Otherwise do something with the API data and send a response
        else {
            res.send(body)
        }
    });
});

【讨论】:

    【解决方案2】:

    对于 Node.js,请使用 request

    例子:

    var request = require('request');
    request('http://www.google.com', function (error, response, body) {
      console.log('error:', error); // Print the error if one occurred
      console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
      console.log('body:', body); // Print the HTML for the Google homepage.
    });
    

    http://www.google.com 替换为您的网址。您需要查看是否需要使用其他 API 进行授权;否则你会得到 HTTP 401。

    【讨论】:

      猜你喜欢
      • 2023-03-18
      • 2021-05-15
      • 1970-01-01
      • 2018-11-19
      • 2021-06-16
      • 2018-01-02
      • 2022-01-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多