我有一个包裹着电子的网络应用。电子应用程序会过滤Web请求,并将其重定向到本地https
服务器处理。
session.defaultSession.webRequest.onBeforeRequest({urls:["*://capture.api.url/*"]}, (details, callback) => {
// here all matching filter requests will end up e.g. https://capture.api.url/test
const url = new URL(details.url);
// redirect to the local https server
callback({
redirectURL: `https://localhost:12345${url.pathname}${url.search}${url.hash}`
});
});
此位有效,但仅适用于GET
方法,然后由服务器处理请求
const httpsOptions = {
key: fs.readFileSync(path.join(__dirname, "server-key.pem")),
cert: fs.readFileSync(path.join(__dirname, "server-cert.pem"))
};
this.server = https.createServer(
httpsOptions,
(req /* : IncomingMessage */, res /* : ServerResponse */) => {
// add CORS headers
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Methods",
"GET,POST,PUT,PATCH,DELETE,HEAD,OPTIONS"
);
res.setHeader(
"Access-Control-Allow-Headers",
"Content-Type, Origin, Accept, Authorization, Content-Length, X-Requested-With"
);
// handle request...
res.writeHead(200);
res.end();
}
);
this.server.listen(port);
[就像我在GET
请求中提到的那样,但是对于POST
,发出了飞行前OPTIONS
请求。然后将其重定向,它甚至在没有到达我的本地服务器的情况下也会失败,并在控制台中出现以下错误:
已被CORS策略阻止从源“ https://capture.api.url/search”访问“ http://localhost:3001”处的XMLHttpRequest:对预检请求的响应未通过访问控制检查:预检请求不允许重定向。
值得一提的是,它发生在开发过程中,其中Web应用程序是在单独的流程上构建和运行,并在localhost:3001
上提供服务,而电子应用程序正在从该端点加载该应用程序。
mainWindow.loadURL(
isDevMode ? "http://localhost:3001" : `file://${__dirname}/app/index.html`
);
当它不是开发人员模式时,它可以正常工作(到目前为止)。有没有办法禁用此飞行前检查?或以某种方式对其进行纠正,以确保它不会失败。
似乎有效,但是我不确定这是正确的方法
// Define our main window size
mainWindow = new BrowserWindow({
height: 920,
width: 1600,
show: false,
webPreferences: {
// turn off webSecurity when in dev mode
webSecurity: !isDevMode,
allowEval: false,
nodeIntegration: true,
preload: path.join(
__dirname,
"node_modules",
"@capacitor",
"electron",
"dist",
"electron-bridge.js"
)
}
});
[我仍将等待其他答案,同时,我将使用此“ hack”。