【问题标题】:Node Express Get request passing a custom headerNode Express 获取传递自定义标头的请求
【发布时间】:2018-10-22 20:36:00
【问题描述】:

我正在尝试制作一个与此 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

【问题讨论】:

    标签: node.js ajax express


    【解决方案1】:

    尝试使用 request-promise 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)
      }
    );
    

    【讨论】:

    • 工作就像一个魅力:)
    【解决方案2】:

    jQuery ajax 函数没有headers 选项。您可以在官方文档http://api.jquery.com/jquery.ajax/ 上阅读有关此功能的信息。他们通过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,你就可以流这个例子了

    var req = http.request(options, function (res) {
      var chunks = [];
    
      res.on("data", function (chunk) {
        chunks.push(chunk);
      });
    
      res.on("end", function () {
        var body = Buffer.concat(chunks);
        // TODO: send data to client
        // res.status(200).json(JSON.stringify(body.toString()))
        console.log(body.toString());
      });
    });
    
    req.end();
    

    【讨论】:

    • 列出的第 16 个参数是 headers:使用 XMLHttpRequest 传输与请求一起发送的附加标头键/值对的对象。它确实有效,我测试过。
    • 好的,我尝试了您的代码,它可以保存数据:) 但是将 JSON 输出到客户端的格式不正确。
    • @JohnnyBizzle 我错了,用JSON.parse代替JSON.stringify
    猜你喜欢
    • 2015-09-08
    • 2012-11-17
    • 2012-10-19
    • 2011-02-23
    • 2016-11-08
    • 2020-03-16
    • 1970-01-01
    • 2014-04-22
    • 2017-08-09
    相关资源
    最近更新 更多