我有一个 Google Chrome 扩展(GCE),它将向我的服务器(Nginx - 后端 Golang)发出请求
我已经在后端配置了 CORS,我可以轻松地使用 Postman 向我的服务器创建任何 HTTP 方法,或者在我的终端中执行 CURL,而不会出现 CORS 问题 响应头将包含在下面的 CORS 头中
但是对于我的GCE,我只能成功发出GET请求。对于 POST 请求,我遇到了问题
这是我的 mainfest.json 文件
{
"manifest_version": 3,
"name": "Extension Name",
"version": "1.0",
"description": "Description",
"permissions": [
"activeTab",
"storage"
],
"host_permissions": [
"https://example.com/*"
],
"action": {
"default_popup": "popup.html"
}
}
我的 POST 功能
submitButtonProductCfg.addEventListener('click', () => {
const productName = document.getElementById("product-cfg-name").value;
const link = backendURL + "/api/extension/v1/products/configs";
chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
// Prepare data for POST request (modify as needed)
const data = {
"name": productName,
};
// Create XHR object
const xhr = new XMLHttpRequest();
// Set up the request
xhr.open('POST', link);
xhr.setRequestHeader("Content-Type", "application/json; charset = UTF-8");
// Set up event listeners
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 300) {
alert("Success");
} else {
console.log(xhr.status);
alert("Err");
}
};
xhr.onerror = function() {
console.log(xhr.status);
alert("Err");
};
// Send the request
try {
xhr.send(JSON.stringify(data));
} catch (e) {
console.log("errr ", e);
}
});
});
我也尝试了 Fetch lib
submitButtonProductCfg.addEventListener('click', () => {
const productName = document.getElementById("product-cfg-name").value;
const link = backendURL + "/api/extension/v1/products/configs"; // Replace with actual API endpoint
chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
// Prepare data for POST request (modify as needed)
const data = {
"name": productName,
};
fetch(link, {
method: 'post',
body: JSON.stringify(data),
headers: {
"Content-Type": "application/json; charset = UTF-8"
},
})
.then(response => {
console.log(response)
if (response.ok) {
return response.text();
}
})
.then(text => {
alert("Success");
})
.catch(error => {
console.log(error)
alert("Error " + error);
});
});
});
对于 XML 请求,我收到错误:
Failed to load
对于获取库,我收到错误:
Failed to fetch
请帮助我!
我尝试将获取请求移至 Chrome 选项卡功能之外
submitButtonProductCfg.addEventListener('click', (e) => {
e.preventDefault();
const productName = document.getElementById("product-cfg-name").value;
const link = backendURL + "/api/extension/v1/products/configs"; // Replace with actual API endpoint
// Prepare data for POST request (modify as needed)
const data = {
"name": productName,
};
fetch(link, {
method: 'post',
body: JSON.stringify(data),
headers: {
"Content-Type": "text/plain"
},
})
.then(response => {
console.log(response)
if (response.ok) {
return response.text();
}
})
.then(text => {
alert("Success");
})
.catch(error => {
console.error(error)
alert("Err " + error.value);
});
});
现在效果很好