Javascript 未在标头Node.js控制台应用程序中发送userAgent
我刚刚开始学习javascript和https请求。我在Visual Studio 2017中工作,我根据模板创建了一个空白javascript控制台应用程序,并添加了以下代码Javascript 未在标头Node.js控制台应用程序中发送userAgent,javascript,node.js,https,console,request,Javascript,Node.js,Https,Console,Request,我刚刚开始学习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 }; con
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."}
当我在浏览器中导航到时,我会得到正确的响应。为什么我不能在javascript控制台中执行相同的操作?这是因为特定的API在没有用户代理头的情况下阻止了任何请求 只需添加标题,即可正常工作:
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
和https
相同)
尝试:
您需要在请求的
headers
属性options
const options = {
hostname: 'api.gdax.com',
path: '/products/BTC-USD/stats',
method: 'GET',
agent: false,
headers: { 'User-Agent': 'Mosaic/1.0' }
};
const options = {
hostname: 'api.gdax.com',
path: '/products/BTC-USD/stats',
method: 'GET',
agent: false,
headers: { 'User-Agent': 'Mosaic/1.0' }
};