【发布时间】: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