【问题标题】:How to enable fetch POST in chrome extension contentScript?如何在 chrome 扩展内容脚本中启用获取 POST?
【发布时间】:2019-04-10 21:37:31
【问题描述】:

我正在尝试在 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”。所以,我的标题似乎没有被忽略。但是,“接受”标头确实通过了。

这是服务器上的标头:

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"

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

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

【问题讨论】:

  • 可能是 Chrome 中的错误。尝试在您的后台脚本中发出请求(将来我们会have to,无论如何)。
  • @xOxxOm 刚刚在后台脚本中试了一下,还是一样。谢谢。
  • 如果我删除 mode: "no-cors" 对我有用,但当然只能在 http 网页上使用 - 因为内容脚本无法从 https 页面发出 http 请求。
  • 奇怪。它对我不起作用。如果我使用 http 而不是 https,我会收到此错误:contentScript.js:133 Mixed Content: The page at 'https:....xyz.com/754182173.html' was loaded over HTTPS, but requested an insecure resource 'http:....abc.com/api/save'. This request has been blocked; the content must be served over HTTPS.
  • 确保在编辑内容脚本时重新加载扩展程序和网页。

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


【解决方案1】:

你需要写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);
        }
    });

【讨论】:

  • @Rana 你为什么把'result=' + request.data 作为正文?我在接收方看到了这个body: { result: '[object Object]' }。为什么我不能将 request.data 作为 json 对象发送?
  • 嗨@newman,这是使用仅附加结果字符串的格式,没有任何特定目的。您只能更改它 request.data。关于对象请检查您的请求是否正确以调试代码
  • @LeoColman 这很有帮助,谢谢。我正在尝试执行多个fetch GET 请求——来自调用者的request 是一个URL 数组。我尝试了for loop,然后在其中获取每个URL,但是当我尝试将for loop 包装在async 函数或@ 987654330@。任何想法将不胜感激,谢谢!
  • @RajputVikashRana 是答案的作者,我只做了一个编辑 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-15
  • 1970-01-01
  • 2011-09-28
相关资源
最近更新 更多