node.js https.get()触发错误ECONNREFUSED [英] node.js https.get() fires error ECONNREFUSED
问题描述
OAuth舞蹈的一个步骤涉及交换通过回调接收的访问令牌代码。特别是对于Facebook服务器端身份验证,以下https GET请求返回响应正文中的访问代码:
One of the steps of the OAuth dance involves exchanging a code received via a callback for an access token. Specifically for Facebook server side auth, the following https GET request returns the access code in the response body:
https://graph.facebook.com/oauth/access_token?
client_id=YOUR_APP_ID
&redirect_uri=YOUR_REDIRECT_URI
&client_secret=YOUR_APP_SECRET
&code=CODE_GENERATED_BY_FACEBOOK
尝试连接时,Node.js会触发错误:
Node.js fires an error when attempting to connect thus:
https.get( /**String | Object*/ options, function ( res ) {
res.setEncoding( 'utf8' );
res.on( 'data', function ( data ) {
// parse response body
} );
} ).on( 'error',function ( e ) {
Log.w( TAG, "Error requesting access_token", e );
} ).end();
错误是:
{ code: 'ECONNREFUSED',
errno: 'ECONNREFUSED',
syscall: 'connect' }
这个调用与wget / curl一起工作正常,所以它不是传出防火墙规则等问题。节点请求有什么问题?
The call works fine with wget/curl so its not a question of outgoing firewall rules or such. What is wrong with the node request?
推荐答案
原来问题是https证书验证失败。来自节点的https.request() docs :
Turns out the issue was https certificate verification failure. From node's https.request() docs:
rejectUnauthorized :如果为true,则根据提供的CA列表验证服务器证书。如果验证失败,则会发出错误事件。在发送HTTP请求之前,验证发生在连接级别。默认为true。
rejectUnauthorized: If true, the server certificate is verified against the list of supplied CAs. An 'error' event is emitted if verification fails. Verification happens at the connection level, before the HTTP request is sent. Default true.
除非明确提供,否则http [s]。[request | get]将使用忽略 tls.connect()选项,包括 rejectUnauthorized 标志。因此需要修改对get(或request)的调用:
Unless explicitly provided, http[s].[request|get] will use the global Agent which ignores tls.connect() options including the rejectUnauthorized flag. The call to get (or request) needs to be modified thus:
var options = require('url').parse( /**String*/ url );
options.rejectUnauthorized = false;
options.agent = new https.Agent( options );
https.get( /**Object*/ options, function ( res ) {
// handle response & body
} ).on( 'error',function ( e ) {
// handle errors
} ).end();
这篇关于node.js https.get()触发错误ECONNREFUSED的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!