简体   繁体   中英

How can I resolve API requests that work properly in postman and in my browser, but return TypeError: Failed to fetch when used with fetch()?

I am attempting to access an API when a button is clicked on a webpage using the fetch() command. My code as is works with the omdb API, but when I try to use Flixed ( https://flixed.io/docs/api#overview ) (both APIs are related to getting streaming data for movies/tv) the query fails with TypeError: Failed to fetch.

However, when I try to use an identical URL in my browser or in postman, the query returns JSON data as expected. I suspect that there is a cors error happening, but the message I receive back has status 200 and I'm not sure what I need to do to resolve it.

Here is the code I am running inside of a function in my script tag: `

    fetch("https://api.flixed.io/v1/movies/0208092?idType=imdb&apiKey=8MqjZtMPW1LUUEydpqjzULeQ6EmBfbEg", {
      method: 'GET',
    })
      .then(response => {
        return response.json();
      })
      .then((data) => {
        results = document.getElementById("resultsText");
        results.innerText = data;
        results.style.display = "block";
      })
      .catch((error) => {
        results = document.getElementById("resultsText");
        results.innerText = error.message;
        results.style.display = "block";
      });

`

I have tried searching on StackOverflow for similar issues, and have experimented with different headers and cors settings, but I have not been able to get any response other than the TypeError when accessing the Flixed API. I am unfortunately relatively new to web dev in particular, so my knowledge of API requests is limited, and my troubleshooting skills in this matter are limited to what I can find online. All the explanations I have been able to find online relating to cors issues seem to assume a level of pre-understanding I don't have, despite my attempts to implement them. So any level of explanation for such a solution would be greatly appreciated.

Try put no-cors in fetch:

fetch("https://api.flixed.io/v1/movies/0208092?idType=imdb&apiKey=8MqjZtMPW1LUUEydpqjzULeQ6EmBfbEg", {
  method: 'GET',
  mode: 'no-cors'
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM