2017-11-15 4 views
1

javascriptとhttps要求を学習し始めました。 Visual Studio 2017で作業しています。テンプレートから空のjavascriptコンソールアプリケーションを作成し、次のコードを追加しました。ヘッダー、Node.jsコンソールアプリケーションでuserAgentを送信しない

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のコンソールで同じことをすることができないのですか?

答えて

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(); 
+1

headersプロパティにUser-Agentヘッダーを設定する必要があります! – FriendlyUser3

0

手動でヘッダーを設定する必要があります。すべての可能なリクエストオプションについてはhttpのドキュメントを参照してください(これはhttphttpsと同じです)。

試してみてください。

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

あなたはあなたに感謝し、明示的に働いていたあなたの要求options

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