Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
144 views
in Technique[技术] by (71.8m points)

javascript - Fetch won't return any results

I have never used fetch before, and have followed the documentation, however, no results are being returned from my backend. When I submit the form, the url changes, and all appears fine in my console, but no response from my express backend.

The following code is what I have after my form in a script tag. Can someone please advise?

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'}
    })
  );
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

Please log in or register to answer this question.

1 Answer

0 votes
by (71.8m points)

You could try creating a promise and then handling the value returned by the fetch with resolve and reject

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);
          });
    });

};

You would then call it like

getSample(...)
.then(results => {
     //Code when fetch is successful
}.catch(error => {
    //Code when fetch fails
};

I think the problem with it returning nothing is that getSample is an async function, but I imagine you're calling it within a program that isn't async, and so whatever code comes after getSample is using trying to use the value returned from getSample, but nothing's been returned yet, so it's using an empty value. Either that or the return of getSample is happening before the fetch completes. I'm not sure of the exact order that things happen, but a promise should fix your problem


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to JiKe DevOps Community for programmer and developer-Open, Learning and Share
...