首页 > 解决方案 > 获取 Chrome 扩展的 Post 请求失败

问题描述

目前,我正在尝试为我的 chrome 扩展程序发出发布请求,并且我一直Fetch Failed在控制台中收到响应。

popup.html

<!DOCTYPE html>
<html>
  <head>
    <title>Tube Hunt: Community Curated YouTube Recommendations</title>
    <script src="popup.js"></script>
  </head>
  <body style="width: 15rem; height: 15rem">
    <div class="container-fluid" style="padding: 10px">
      <a
        href="https://www.reddit.com/r/TubeHunt/"
        target="_blank"
        class="badge badge-secondary"
        >/r/TubeHunt</a
      >
      <form
        name="inputForm"
        action="https://us-central1-tube-hunt.cloudfunctions.net/app/api/channel/submit"
        method="POST"
      >
        <input
          id="url"
          value="https://www.youtube.com/c/PickUpLimes"
          name="url"
        />
        <button type="submit" id="newDetails">Submit</button>
      </form>
      <button type="button" id="getChannels">Get Channels</button>
    </div>
  </body>
</html>

popup.js

btn.addEventListener("click", function (e) {
      e.preventDefault();
      if (url.value) {
        console.log(url.value);
        let data = new FormData();
        const myHeaders = new Headers({
          Accept:"application/json, application/xml, text/plain, text/html
        });
        const baseURL ="myurl";
        data.append("url", `${url.value}`);
        fetch(baseURL, {
          headers: myHeaders,
          method: "POST",
          body: data,
          mode: 'cors'
        })
          .then((res) => {
            console.log(res)
            return res.text()
          })
          .then((html) => console.log(html))
          .catch(function (err) {
            console.log("Problem");
            console.log(err);
          });
      }
    });

根据要求,这里是manifest.json. 如您所见,我在这里添加了我的服务器的权限。

{
    "manifest_version": 2,
    "name": "Tube Hunt",
    "version": "0.1",
    "content_scripts": [
        {
            "matches": [
                "https://www.youtube.com/*"
            ],
            "js": [
                "jquery.min.js",
                "content.js",
                "background.js"
            ]
        }
    ],
    "background": {
        "scripts": [
            "background.js"
        ]
    },
    "browser_action": {
        "default_icon": "download.png",
        "default_popup": "popup.html"
    },
    "permissions":[
        "https://us-central1-tube-hunt.cloudfunctions.net/app/api/*"
    ]
}

目前,我可以访问我的服务器,但从中得到一个500错误代码。我能够成功执行 GET 请求,而不是 POST 请求。除了我的研究之外,我还发现这个用于获取的链接并没有多大帮助。

标签: javascriptpostgoogle-chrome-extensionfetchcrud

解决方案


终于解决了!感谢@wOxxOm 的所有帮助。

结果我一直收到500错误,因为我完全忘记了我的合作伙伴设置服务器/数据库设置它,以便特定频道不能有相同的正文内容。除此之外,上面的代码对我有用。感谢你的帮助!


推荐阅读