OAuth 舞蹈的其中一个步骤涉及交换通过回调接收到的代码以获取访问 token 。专门针对 Facebook 服务器端身份验证,以下 https GET 请求在响应正文中返回访问代码:
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 会引发错误:
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 一起工作正常,所以它不是传出防火墙规则等的问题。 Node 请求有什么问题?
最佳答案
原来问题是 https 证书验证失败。来自 Node 的 https.request() docs :
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 标志。获取(或请求)的调用需要这样修改:
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,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15929167/