leo*_*ess 12 javascript post google-chrome fetch-api
我使用以下代码通过 Fetch API 将用户位置发布到我自己的后端服务:
window.onload = () => {
let getPosition = (options) => {
return new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(resolve, reject, options);
});
};
getPosition().then(pos => {
const data = new FormData();
data.append('latitude', String(pos.coords.latitude));
data.append('longitude', String(pos.coords.longitude));
fetch('/', { // <--- error is thrown in this line
method: 'POST',
body: data
}).then(response => {
if (!response.ok) {
throw Error('Data sent - Network response NOT OK');
} else {
console.log('Data sent - Network response OK')
}
});
});
};
Run Code Online (Sandbox Code Playgroud)
这完美地工作,后端服务发回一个积极的空响应。Data sent - Network response OK记录在浏览器的控制台中,一切都很好,除了紧随其后,记录如下:
为什么Fetch failed loading: POST即使 POST 成功,响应正常,Chrome 网络选项卡中的状态代码是200 OK?我的代码有问题吗?
rew*_*olf 17
我的行为和你看到的一样。我的服务器以(空响应)和空(内容长度 = 0)响应响应POST请求204。我尝试将其更改为仅以“确定”消息响应(编辑:实际上只是现在返回创建的对象)并且fetch错误日志消失了。
在我看来fetch,即使请求成功,当响应正文为空时(至少在 Chrome 中)也会错误地记录“Fetch Failed”。
The*_*ppo 11
发生这种情况是因为您没有读取空响应正文。我注意到这一点,因为 Djangobroken pipe在服务器端触发了一个错误。要解决这个问题,只需将空的正文读出即可。
async function fetchSomething() {
const response = await fetch(url, {
method: 'POST'
})
await response.text()
return response.ok
}
Run Code Online (Sandbox Code Playgroud)