JavaScript的POST fetch请求发送为OPTIONS。

3
我正在学习JavaScript,并且正在制作一个账户登录页面作为学习项目。服务器使用Python的Flask。fetch函数似乎不按照我的要求工作。首先,它发送的是一个选项请求而不是POST,尽管我指定了POST。另一件事是服务器没有接收到数据,数据为空。以下是代码:

var content = JSON.stringify({'username': username, 'password': password}) //username and password are user inputs, I had them print and these work fine.
var response = fetch(url+"/api/login", {
      method: "POST",
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
      },
      body: content
    })
.then(response => {
  console.log("Success") //this doesn't print.
})


1
听起来你正在进行跨域调用。它在发布之前进行握手。 - epascarello
https://dev59.com/JFoT5IYBdhLWcg3wnQj9#38410411 - epascarello
2个回答

2

这是一个预检请求

通过返回正确的CORS头处理选项请求。

然后还要处理POST请求,由于API和网站的新CORS标准,这两个都是必需的。


-2
我遇到了同样的问题,通过在选项字典中添加 mode: "no-cors" 来解决它,代码如下:
var response = fetch(url+"/api/login", {
  method: "POST",
  mode: "no-cors",
  headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
  },
  body: content
})
.then(response => {
  console.log("Success") //this doesn't print.
})

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接