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
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: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.