Search code examples
javascriptjqueryapingrok

Issue with newsapi.org API and JQuery


I am getting the following error message:

Failed to load resource: the server responded with a status of 426 (Upgrade Required)" error on using JQuery to GET results from https://newsapi.org/v2/top-headlines?country=in&apiKey=..... using proxy-https://cors-anywhere.herokuapp.com/ on a ngrok hosted https site and the localhost too.

But the same process works if I use http instead of https i.e. https://cors-anywhere.herokuapp.com/https://newsapi.org/... and use the http ngrok site.

This is the response I get if I use http-

{status: "error", code: "corsNotAllowed",…} code: "corsNotAllowed" message: "Requests via the browser are not allowed on the Developer plan, except from localhost." status: "error"}

Is there a workaround for this? Will this error go it I host it properly using my domain and by an ssl ?


Solution

  • You are trying to access an API which is not accepting requests from a website (except from localhost). If the browser comes across a request which is cross-origin, it tries to make a pre-flight request (an initial request to ask the server, it is okay to fetch from this remote address, which is different than the current domain). If the pre-flight request is not responded with a successful message, the Ajax request fails. This behavior is called CORS and it must be supported by the API.

    Your API does not seem to allow i.e. it actually forbids CORS requests explicitly. This is usually done, if the API wants to force the developer to make the request on the server-side. The benefit of this is, that the access key is not sent along with the JavaScript code to the visitor of the website but rather it stays on the server.

    Try to make the request on your server and then send the data to your front-end from your own server. This also allows to use your own authentication. You could also use a web service like CORS everywhere, but keep in mind that this service has access to all data you are sending and receiving (and it is able to modify the data both-ways).