gpt4 book ai didi

google-chrome-extension - 我如何解决扩展中的 Access-Control-Allow-Origin

转载 作者:行者123 更新时间:2023-12-04 02:29:31 26 4
gpt4 key购买 nike

由于同源策略,我的请求失败了,但是我是否可以在扩展中使用 webRequest api 修改 header 来解决这个问题?

最佳答案

将此添加到您的 background.js 文件中:

/**
* Force Access-Control-Allow-Origin
*
* Ideally, we'll want to remove this for production,
* and actually set the header server side instead.
*/
chrome.webRequest.onHeadersReceived.addListener(function onHeadersReceived(resp) {
var len = resp.responseHeaders.length;
while(--len) {
if(resp.responseHeaders[len].name.toLowerCase() === "access-control-allow-origin") {
resp.responseHeaders[len].value = "*";
break;
}
}
if (len === 0) { //if we didn't find it len will be zero
resp.responseHeaders.push({
'name': 'Access-Control-Allow-Origin',
'value': '*'
});
}
return {responseHeaders: resp.responseHeaders};
}, {
urls: ['*://*.YOU-API-DOMAIN.com/*', '*://localhost/*'],
/*TYPES: "main_frame", "sub_frame", "stylesheet", "script",
"image", "object", "xmlhttprequest", "other" */
types: ['xmlhttprequest']
}, ['blocking', 'responseHeaders']);

并将这些添加到您的 manifest.json 权限中:

"webRequest",
"webRequestBlocking"

重新加载扩展,你应该可以开始了!

关于google-chrome-extension - 我如何解决扩展中的 Access-Control-Allow-Origin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13819541/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com