我正在学习JavaScript,我正在制作一个帐户登录页面作为学习项目。服务器使用Python的Flask。获取功能似乎没有按照我想要的方式工作。其一,它发送选项请求而不是 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.
})
如果您想要正确的响应,请务必使用 cors... 我就是这样做的。请求很好,但是 .then() 不适合 console.logging...
var response = fetch(url+"/api/login", {
method: "POST",
mode: "cors",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: content
})
.then(r => r.text().then(console.log));
我发现了同样的问题,并通过将
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.
})