gpt4 book ai didi

google-chrome - 如何在 chrome 扩展 contentScript 中启用获取 POST?

转载 作者:行者123 更新时间:2023-12-04 01:20:19 25 4
gpt4 key购买 nike

我正在尝试在 chrome 扩展中调用 REST API。我设法使 fetch GET 工作,但无法使 POST 工作。服务器端的主体始终为空。这是我的提取请求:

  let url = "http://localhost:3000/api/save/one"
fetch(url, { method: "POST", headers: { "Accept": "application/json", "Content-Type": "application/json; charset=utf-8" }, mode: "no-cors", body: JSON.stringify(json) })
.then(resp => console.log(resp))

当我检查服务器上的请求时,我确实注意到服务器上的内容类型始终是“text/plain;charset=UTF-8”。所以,我的标题似乎没有被忽略。但是,“接受”标题确实通过了。

这是服务器上的 header :
accept:"application/json"
accept-encoding:"gzip, deflate, br"
accept-language:"en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7"
cache-control:"no-cache"
connection:"close"
content-length:"306"
content-type:"text/plain;charset=UTF-8"

如果我从我的提取 header 中删除“接受”,我会在服务器上得到这个:
accept:"*/*"
accept-encoding:"gzip, deflate, br"
accept-language:"en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7"
cache-control:"no-cache"
connection:"close"
content-length:"306"
content-type:"text/plain;charset=UTF-8"

对此有何解释?那么,如何使 POST 工作呢?

最佳答案

您需要编写 post 方法的代码

听众

背景.js:

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {    
if (request.contentScriptQuery == "getdata") {
var url = request.url;
fetch(url)
.then(response => response.text())
.then(response => sendResponse(response))
.catch()
return true;
}
if (request.contentScriptQuery == "postData") {
fetch(request.url, {
method: 'POST',
headers: {
'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
},
body: 'result=' + request.data
})
.then(response => response.json())
.then(response => sendResponse(response))
.catch(error => console.log('Error:', error));
return true;
}
});

调用者

Content_script.js

chrome.runtime.sendMessage(
{
contentScriptQuery: "postData"
, data: JSONdata
, url: ApiUrl
}, function (response) {
debugger;
if (response != undefined && response != "") {
callback(response);
}
else {
debugger;
callback(null);
}
});

关于google-chrome - 如何在 chrome 扩展 contentScript 中启用获取 POST?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53405535/

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