javascript - Fetch 不会返回任何结果
问题描述
我以前从未使用fetch
过,并且遵循了文档,但是,我的后端没有返回任何结果。当我提交表单时,网址发生了变化,并且在我的控制台中一切正常,但我的快速后端没有响应。
以下代码是我在脚本标签中的表单之后的代码。有人可以建议吗?
async function getSample(url = `http://localhost:3000/lookup/${url}`, data = {}) {
const response = await fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
return response.json();
}
document.getElementById('search').addEventListener('submit', function(e) {
event.respondWith(
new Response(myBody, {
headers: {'Content-Type': 'application/json'}
})
);
});
解决方案
您可以尝试创建一个承诺,然后使用 resolve 和 reject 处理 fetch 返回的值
async function getSample(url = `http://localhost:3000/lookup/${url}`, data = {}){
return new Promise(function (resolve, reject) {
fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}).then(async response => {
if (response.ok) {
response.json().then(json => resolve(json));
} else {
response.json().then(json => reject(json));
};
}).catch(async error => {
reject(error);
});
});
};
然后你会这样称呼它
getSample(...)
.then(results => {
//Code when fetch is successful
}.catch(error => {
//Code when fetch fails
};
我认为它不返回任何内容的问题在于它getSample
是一个异步函数,但我想你是在一个非异步的程序中调用它,所以后面的任何代码都在getSample
尝试使用从返回的值getSample
,但什么都没有尚未返回,因此它使用的是空值。在 fetch 完成之前,或者 getSample 的返回发生。我不确定事情发生的确切顺序,但承诺应该可以解决您的问题
推荐阅读
- c - C 冒泡排序最大的值变成0
- javascript - 减少 setState 中的计数器
- sql - 使用 SQL 创建 ID X-ref 表
- r - 如何使用 dplyr 将变量从数字转换为具有唯一级别的因子
- node.js - 节点js中的SSH命令突然重试
- objective-c - iOS 11 视觉。冻结前只能执行 VNImageBasedRequest 15 次
- javascript - 不允许我在同一个按钮上提交和点击
- ruby-on-rails - Rails - 将搜查结果转换为 xls
- java - 当我尝试通过 javaFX 中的不同场景传递值时,Setter 方法不起作用
- python - 使用特定分隔符将 Pandas 转换为字符串