Node Express获取传递自定义标头的请求

时间:2018-10-22 20:36:00

标签: node.js ajax express

我正尝试发出与该jQuery等效的get请求:

  $.ajax({
    headers: { 'X-Auth-Token': 'YOUR_API_KEY' },
    url: 'http://api.football-data.org/v2/competitions/BL1/standings',
    dataType: 'json',
    type: 'GET',
  }).done(function(response) {       
    console.log(response);
  });

但是,我还没有弄清楚如何使用nodejs-express。此代码来自附加到主应用程序的api路由模块。 该请求似乎有效,正在收集数据,但没有结束。另外,从浏览器进行检查时,我无法在请求中看到自定义标头。

   app.get('/api/:league', function(req, res, next) {

      var apiKey = process.env.API_KEY;    
      let url = 'api.football-data.org';

      var options = {
        host: url,
        method: 'GET',
        path: 'v2/competitions/BL1/standings',
        headers: {
          'X-Auth-Token': apiKey
        }
      };

      let data = "";
      var getReq = http.request(options,function(resp){

         console.log("Connected");        
         resp.on("data", chunk => {
          data += chunk;
         });

         resp.on("end", () => {
           console.log("data collected");
         });
      });

      getReq.on("error", (err) => console.log("OOPS!", err));

      getReq.end(JSON.stringify(data));

  })    

Link to project

2 个答案:

答案 0 :(得分:1)

尝试使用请求承诺的npm软件包。https://www.npmjs.com/package/request-promise

var rp = require(request-promise);

const baseUrl = 'api.football-data.org/v2/competitions/BL1/standings';
const apiKey = process.env.API_KEY;

var options = {
  method: 'GET',
  uri: baseUrl,
  headers: {
      'X-Auth-Token': apiKey
  },
  json: true
};

rp(options)
.then(function (response) {
  console.log(response)
  }
);

答案 1 :(得分:1)

jQuery ajax函数没有List<String> CHOICES = ["a", "b", "c"] pipeline { agent any options { timestamps() } parameters { choice(name: 'CHOICE', choices: CHOICES, description: 'Who to greet?') } stages { stage("test") { steps { echo params.CHOICE } } } } 选项。您可以在官方文档http://api.jquery.com/jquery.ajax/中阅读有关此功能的信息。他们通过headers函数方式自定义请求标头:

beforeSend

使用$.ajax({ beforeSend: function (request) { request.setRequestHeader("X-Auth-Token", 'YOUR_API_KEY'); }, url: 'http://api.football-data.org/v2/competitions/BL1/standings', dataType: 'json', type: 'GET', }).done(function (response) { console.log(response); }); ,您可以展示此示例

http node lib