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

new*_*man 3 post google-chrome fetch google-chrome-extension

我正在尝试在 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))
Run Code Online (Sandbox Code Playgroud)

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

这是服务器上的标头:

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"
Run Code Online (Sandbox Code Playgroud)

如果我从我的提取标头中删除“接受”,我会在服务器上得到这个:

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"
Run Code Online (Sandbox Code Playgroud)

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

小智 6

您需要编写 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;
    }
});
Run Code Online (Sandbox Code Playgroud)

呼叫者

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);
        }
    });
Run Code Online (Sandbox Code Playgroud)