1. 在主进程中引入Electron的session模块:
const { session } = require('electron');
2. 创建一个新的session实例:
const mySession = session.fromPartition('mySession');
3. 在session实例中设置请求头:
mySession.webRequest.onBeforeSendHeaders((details, callback) => {
details.requestHeaders['Origin'] = 'http://localhost:3000'; // 设置请求头中的Origin字段
callback({ cancel: false, requestHeaders: details.requestHeaders });
});
其中,'http://localhost:3000'是你的应用程序的地址,需要根据实际情况进行修改。
4. 在fetch或ajax请求中指定使用该session实例:
fetch('http://example.com', { session: mySession })
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
或者:
$.ajax({
url: 'http://example.com',
xhrFields: {
withCredentials: true,
},
beforeSend: function(xhr) {
xhr.setRequestHeader('Origin', 'http://localhost:3000');
},
success: function(data) {
console.log(data);
},
error: function(error) {
console.error(error);
},
});
其中,'http://example.com'是你要请求的地址,需要根据实际情况进行修改。
通过以上步骤,就可以在Electron中解决fetch或ajax请求的跨域问题了。
网友回复