首页 > 解决方案 > 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'}
    })
  );
});

标签: javascriptfetch

解决方案


您可以尝试创建一个承诺,然后使用 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 的返回发生。我不确定事情发生的确切顺序,但承诺应该可以解决您的问题


推荐阅读