【问题标题】:Not sending userAgent in header, Node.js console application不在标头中发送 userAgent,Node.js 控制台应用程序
【发布时间】:2018-04-29 00:33:03
【问题描述】:

我刚刚开始学习 javascript 和 https 请求。我在 Visual Studio 2017 中工作,我从模板创建了一个空白的 javascript 控制台应用程序并添加了以下代码。

const https = require('https');

const options = {
    hostname: 'api.gdax.com',
    path: '/products/BTC-USD/stats',
    method: 'GET',
    agent: false
};

const req = https.request(options, (res) => {
    console.log('statusCode:', res.statusCode);
    console.log('headers:', res.headers);

    res.on('data', (d) => {
        process.stdout.write(d);
    });
});

req.on('error', (e) => {
    console.error(e);
});
req.end();

我从服务器得到的响应是

{"message":"User-Agent header is required."}

当我在浏览器中导航到 https://api.gdax.com/products/BTC-USD/stats 时,我得到了正确的响应。为什么我不能在 javascript 控制台中做同样的事情?

【问题讨论】:

    标签: javascript node.js https console request


    【解决方案1】:

    这是因为该特定 API 会阻止任何没有 User-Agent 标头的请求。

    只需添加标题,它就可以正常工作:

    const https = require('https');
    
    const options = {
      hostname: 'api.gdax.com',
      path: '/products/BTC-USD/stats',
      method: 'GET',
      agent: false,
      headers: {
        'User-Agent': 'something',
      },
    };
    
    const req = https.request(options, res => {
      console.log('statusCode:', res.statusCode);
      console.log('headers:', res.headers);
    
      res.on('data', d => {
        process.stdout.write(d);
      });
    });
    
    req.on('error', e => {
      console.error(e);
    });
    req.end();
    

    【讨论】:

      【解决方案2】:

      您需要手动设置标题。有关所有可能的请求选项,请参阅 http 文档(httphttps 相同)。

      尝试:

      const options = {
          hostname: 'api.gdax.com',
          path: '/products/BTC-USD/stats',
          method: 'GET',
          agent: false,
          headers: {
              'User-Agent': 'Foo/1.0',
          },
      };
      

      【讨论】:

        【解决方案3】:

        您需要在请求optionsheaders 属性中显式设置User-Agent 标头

        const options = {
            hostname: 'api.gdax.com',
            path: '/products/BTC-USD/stats',
            method: 'GET',
            agent: false,
            headers: { 'User-Agent': 'Mosaic/1.0' }
        };
        

        【讨论】:

          猜你喜欢
          • 2012-08-14
          • 2011-02-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多