如何从服务器端发出API请求?

时间:2019-12-29 14:33:11

标签: node.js amazon-web-services api

我想从Coinmarketcap API发出请求。他们不允许使用CORS配置,因为安全很重要,该选项是通过浏览器通过自己的后端服务路由调用来在浏览器中执行该操作。

人们对我说,他们使用了几种带有免费层的无服务器选项,其中包括AWS Lambda,Google Cloud Functions,Azure Functions。 但是我不知道该怎么做,我想使用Aws Lambda,我需要做什么?

那是我的node.js代码:



const rp = require('request-promise');
const requestOptions = {
  method: 'GET',
  uri: 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest',
  qs: {
    'start': '1',
    'limit': '5000',
    'convert': 'USD'
  },
  headers: {
    'X-CMC_PRO_API_KEY': 'b54bcf4d-1bca-4e8e-9a24-22ff2c3d462c' //that isn't my real api key
  },
  json: true,
  gzip: true
};

rp(requestOptions).then(response => {
  console.log('API call response:', response);
}).catch((err) => {
  console.log('API call error:', err.message);
});

1 个答案:

答案 0 :(得分:0)

AWS Lambda函数可以帮助您执行api并返回响应。您可能还需要AWS API Gateway才能将响应从lambda连接到您的api。 lambda中的代码如下所示:

const rp = require('request-promise');

exports.handler = async (event) => {
  const requestOptions = {
    method: 'GET',
    uri: 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest',
    qs: {
      'start': '1',
      'limit': '5000',
      'convert': 'USD'
    },
    headers: {
      'X-CMC_PRO_API_KEY': 'b54bcf4d-1bca-4e8e-9a24-22ff2c3d462c' //that isn't my real api key
    },
    json: true,
    gzip: true
  };

  const response = rp(requestOptions);
  console.log(response);
  return response;
}

基本上将输入传递给事件对象,然后可以像普通对象一样使用。另请参阅-https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-create-api-as-simple-proxy-for-lambda.html