skip to Main Content

I am trying to fetch search results by using youtube autocomplete API but I am getting an error:

const YOUTUBE_SEARCH_API = http://suggestqueries.google.com/complete/search?client=firefox&ds=yt&q=
const getSearchSuggetsions = async (text) => {
  const data = await fetch(YOUTUBE_SEARCH_API + text);
  const json = await data.json();
  console.log(json)
}

ERROR
Access to fetch at http://suggestqueries.google.com/complete/search?client=firefox&ds=yt&q= from origin http://localhost:3000 has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

And when I write {mode: ‘no-cors’} then I get a response in the network tab but don’t get the result in the console, there was an error that ‘Unexpected end of input’.

2

Answers


  1. The Access-Control-Allow-Origin is something that needs to be set on the server and not on the client. Since you do not control the server, there are two options:

    1. Search for another api that allows you to do a request from anywhere.
    2. You can write your own backend as a wrapper (for example http://localhost:4000/api/search), that takes the parameters, fetches the data using the api and returns the data.
    Login or Signup to reply.
  2. The error happens because of origin policy for security reasons. To solve this issue, you can either setup your own backend or an alternative way is to use the YouTube data API which requires an API key and allows you to make requests from your frontend code.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search