【发布时间】:2018-05-22 02:43:57
【问题描述】:
下面我有两个 http 请求,一个是用 request 发出的,另一个是用 isomorphic-fetch (node-fetch) 发出的。出于某种原因,带有request 的请求有效,但是node-fetch 以错误代码503 回复。 fetch 版本中我缺少什么吗?
const URL = require('url')
const fetch = require('isomorphic-fetch')
const HttpsProxyAgent = require('https-proxy-agent')
const request = require('request');
const url = process.env.URL
const proxy = process.env.PROXY
const requestPromise = function (url, options) {
if (/^\/\//.test(url)) {
url = 'https:' + url;
}
return new Promise(function(resolve, reject) {
return request.call(this, url, options, function (err, res, body) {
if (err) {
throw new Error(err);
}
res.ok = true;
res.json = function () {
return JSON.parse(res.body);
}
return resolve(res);
});
});
};
function getProxy (url) {
const parsedProxyURL = URL.parse(url);
parsedProxyURL.secureProxy = parsedProxyURL.protocol === 'https:';
return parsedProxyURL
}
requestPromise(url, {
agent:new HttpsProxyAgent(getProxy(proxy))
})
.then(console.log)
.catch(console.log)
fetch(url, {
agent:new HttpsProxyAgent(getProxy(proxy))
})
.then(console.log)
.catch(console.log)
【问题讨论】:
-
较新的 Nodejs 应该具有本地提取,同构使用节点提取:github.com/matthew-andrews/isomorphic-fetch/blob/master/… 并且应该可以工作:stackoverflow.com/a/44572328/1641941 您是否尝试将 url 作为字符串作为答案或此处? github.com/bitinn/node-fetch/issues/79
-
@HMR 正如您在上面看到的那样,我正在做您所展示的内容,而不是将字符串传递给
HttpsProxyAgent您可以提供选项。request和node-fetch之间仍然存在差异,这是在request中默认设置的,它可以工作,而在node-fetch中不存在。
标签: javascript node.js proxy request fetch