2017-11-15 4 views
1

저는 자바 스크립트와 https 요청을 배우기 시작했습니다. Visual Studio 2017에서 일하고 있는데 템플릿에서 빈 자바 스크립트 콘솔 앱을 만들고 다음 코드를 추가했습니다. 내가 올바른 응답을 얻을 브라우저에서 https://api.gdax.com/products/BTC-USD/stats로 이동하면헤더, 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."} 

입니다. 왜 내가 자바 스크립트 콘솔에서 같은 일을 할 수 없어?

답변

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' } 
}; 
관련 문제