如何在Chrome扩展程序contentScript中启用获取POST?

时间:2018-11-21 05:01:49

标签: google-chrome post google-chrome-extension fetch

我正在尝试在Chrome扩展程序中调用REST API。我设法获取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”。因此,我的标题似乎没有被传递。但是,“ Accept”标头确实通过了。

这是服务器上的标头:

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"

如果我从提取标头中删除“接受”,则在服务器上获得了此信息:

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工作呢?

1 个答案:

答案 0 :(得分:0)

您需要为post方法编写代码

监听器

background.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);
        }
    });