我正在测试我的 Flask API 的 fetch 函数。我使用 Postman 和 Curl 向 Flask API 发送测试请求,并且我从两者那里得到了正确的响应。但是,当我尝试从 javascript 获取时,出现获取错误。
async function testFetch() {
try {
const response = await fetch("http://localhost:5001/predict", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ "input_data": "This is a sample email" }),
});
if (!response.ok) {
throw new Error("Request failed with status: " + response.status);
}
const prediction = await response.json();
console.log(prediction);
} catch (error) {
console.error(error.message);
}
}
testFetch();
是什么导致了这个问题?
我同时使用了 Curl 和 Postman,并确认我得到了正确的响应,所以问题可能出在我的获取方式上,但我无法调试。
我猜是因为异步功能的缘故。
代码块
if
在返回promise之前执行。
if (!response.ok) {
throw new Error("Request failed with status: " + response.status);
}
当您检查
!response.ok
条件时,response
变量还没有获取到获取的数据。因为此时,response
并没有await
任何承诺。也许你可以把它放在.then()
里面以确保它在请求完成后运行。看看这是否有效:
fetch("http://localhost:5001/predict", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ "input_data": "This is a sample email" }),
})
.then(
if (!response.ok) {
throw new Error("Request failed with status: " + response.status);
}
);