我正在构建一个电子应用程序,需要调用API提供程序尚未启用CORS的API。通常提出的解决方案是使用反向代理,当使用节点和cors在本地运行时,这是很容易做到的 - 像这样:
let port = (process.argv.length > 2) ? parseInt (process.argv[2]) : 8080;
require ('cors-anywhere').createServer ().listen (port, 'localhost');
然后,可以将应用程序配置为通过localhost:8080上的反向代理代理所有请求。
所以,我的问题是:
今天就问这个问题API calls with axios inside a React app bundled in Electron is returning 400
从我所看到的电子调用充当API URL的正常调用意味着它们不受CORS的影响。
现在,当您使用CORS代理打包调用并定期调用代理时,它应该出错400错误,因为它不是CORS调用。这个线程解释了为什么cors-anywhere响应那样=> https://github.com/Rob--W/cors-anywhere/issues/39
实际上我在Electron构建之前从应用程序中删除了我的CORS代理。因为我在浏览器中测试,所以我仍然需要CORS代理进行开发。
希望这可以帮助。
只需在发送请求之前覆盖标头
const filter = {
urls: ['*://*.google.com/*']
};
const session = electron.remote.session
session.defaultSession.webRequest.onBeforeSendHeaders(filter, (details, callback) => {
details.requestHeaders['Origin'] = null;
details.headers['Origin'] = null;
callback({ requestHeaders: details.requestHeaders })
});
将这些代码放在渲染过程中
你有没有尝试过使用fetch()
检查如何使用fetch来制作一个no-cors请求https://developers.google.com/web/updates/2015/03/introduction-to-fetch?hl=en