不在header,Node.js控制台应用程序中发送userAgent

我刚刚开始学习JavaScript和https请求。 我在Visual Studio 2017中工作,我从模板中创build了一个空白的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控制台中做同样的事情?

这是因为特定的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(); 

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

尝试:

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

您需要在您的请求optionsheaders属性中明确设置User-Agentheaders

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