我有nodeApp。它做事。
在特定时间,我需要与野外的 API 进行通信。在像 Postman 这样的 rest 工具中使用 API 很简单:
邮差
Url:
https://epicurl
Headers:
Content-Type : application/json
Accept : application/json
x-key : secret
Body:
{
"some":"kickass"
"data":"here"
}
在邮递员中发送上述内容,我得到了很好的快速回复!是的休息工具。
所以他们的 API 有效,现在我需要在我的 Node.js 应用程序中做出同样的响应。
这就是事情变得奇怪的地方......
请求模块:失败
var request = require('request')
...lots_of_other_stuff...
var options = {
uri: 'https://epicURL',
method: 'POST',
json: true,
headers : {
"Content-Type":"application/json",
"Accept":"application/json",
"x-key":"secretbro"
},
body : JSON.stringify(bodyModel)
};
request(options, function(error, response, body) {
if (!error) {
console.log('Body is:');
console.log(body);
} else {
console.log('Error is:');
logger.info(error);
}
cb(body); //Callback sends request back...
});
以上失败..它抛出了我们都喜欢的good'ol ECONNRESET错误!为什么?谁知道?
https.request() - 工作!
var https = require("https");
https.globalAgent.options.secureProtocol = 'SSLv3_method';
var headers = {
"Content-Type":"application/json",
"Accept":"application/json",
"x-key":"nicetrybro"
}
var options = {
host: 'www.l33turls.com',
port:443,
path: "/sweetpathsofjebus",
method: 'POST',
headers: headers
};
var req = https.request(options, function(res) {
res.setEncoding('utf-8');
var responseString = '';
res.on('data', function(data) {
responseString += data;
});
res.on('end', function() {
var resultObject = responseString;
//Call the callback function to get this response object back to the router.
cb(resultObject);
});
});
req.on('error', function(e) {
console.log(e);
});
req.write(bodyString);
req.end();
但后来我注意到...
如果我在使用请求模块时保留这行代码,那么它就可以工作......
var https = require("https");
https.globalAgent.options.secureProtocol = 'SSLv3_method';
这是否记录在某处而我错过了?有人向我解释这个吗?