gpt4 book ai didi

javascript - 跨源读取阻止 (CORB) API 调用 Chrome 扩展

转载 作者:行者123 更新时间:2023-12-01 00:57:01 24 4
gpt4 key购买 nike

我想通过我的 chrome 扩展程序中的 post 调用 api,问题是无法获取响应数据。

我刚刚在控制台中收到跨源读取阻止 (CORB),但响应为空。

Cross-Origin Read Blocking (CORB) blocked cross-origin response http://127.0.0.1:8080/api/v1/login/ldap with MIME type application/json. See https://www.chromestatus.com/feature/5629709824032768 for more details.

首先我尝试直接调用ajax:

$.ajax({
type: 'POST',
url: 'http://127.0.0.1:8080/api/v1/login/local',
data: postBody,
success: function(resData, status, jqXHR) {
console.log({resData, status, jqXHR});
},
error: function(jqXHR, status) {
console.log({jqXHR, status});
}
});

我尝试将我的ajax调用从content.js移动到background.js,如下所示

背景.js

chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if(request.contentScriptQuery === 'login') {
$.ajax({
type: 'POST',
url: 'http://127.0.0.1:8080/api/v1/login/local',
data: postBody,
success: function(resData, status, jqXHR) {
sendResponse([
{
resData: resData,
status: status,
jqXHR: jqXHR
}, null
]);
},
error: function(jqXHR, status) {
sendResponse([
null, {
status: status,
jqXHR: jqXHR
}
]);
}
});
}
//right here?
return true;
});

内容.js

chrome.runtime.sendMessage({contentScriptQuery: 'login'}, messageResponse =>{
console.log(messageResponse);
});

但在这种情况下我收到以下错误:

"Unchecked runtime.lastError: The message port closed before a response was received."

而且我不知道如何保持端口打开并接收请求正文。或者即使我得到了 body 或仍然遇到了Corb问题。

这是我今天的最后一次尝试,端口仍然关闭:-(

"Unchecked runtime.lastError: The message port closed before a response was received."

chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if(request.contentScriptQuery === 'loginLocal') {
$.ajax({
type: 'POST',
url: 'http://127.0.0.1:8080/api/v1/login/local',
data: postBody
}).then(function(resData, status, jqXHR) {
sendResponse([
{
statuscode: jqXHR.status,
resData: resData,
status: status
}, null
]);
}, function(jqXHR, status) {
sendResponse([
null, {
statuscode: jqXHR.status,
status: status
}
]);
});
return true;
}
});

最佳答案

我更改为 sendRequest - 对我有用:

内容.js

chrome.extension.sendRequest({contentScriptQuery: 'login'}, function(messageResponse) {
const[response, error] = messageResponse;
if(response === null){
console.log(error);
} else {
console.log(response.resData);
}
});

背景.js

chrome.extension.onRequest.addListener(function (message, sender, sendResponse) {
if(message.contentScriptQuery === 'login') {
$.ajax({
type: 'POST',
url: 'http://127.0.0.1:8080/api/v1/login/local',
}).then(function(resData, status, jqXHR) {
sendResponse(sendResponse([
{
resData: resData,
status: status
}, null
]));
}, function(jqXHR, status) {
sendResponse([
null, {
status: status
}
]);
});

return true;
}
});

关于javascript - 跨源读取阻止 (CORB) API 调用 Chrome 扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56479389/

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