How To Overcome Cors Issue With Https://newsapi.org/
Solution 1:
You can solve the Cross Origin issue by proxying from your origin (the web server) to the API server.
Change the calls in the client code to send requests to /api/whatever
(deliberate lack of scheme, host and port there, so it uses the one that served the page). From the client's perspective this is no longer a request to a different host.
I guess that in the action you dispatch, this would correspond to changing the endpoint
property:
endpoint: `/api/top-headlines?country=us&category=business&apiKey=${API_KEY}`
Then set up a path-based proxy in your web server to match routes starting with /api
and proxy them to https://newsapi.org/v2
. For example, using http-proxy-middleware
:
var proxy = require('http-proxy-middleware');
app.use('/api', proxy({target: 'https://newsapi.org/v2'}));
Note that the "Access-Control-Allow-Origin" header is set by the server, not the client, so it's not doing anything useful in your example.
Solution 2:
I was wondering if i can resolve this issue from a client side as i donot have any access to the API internally.
Unfortunately you can't; the server behind the request has to set the correct CORS headers for CORS to work (you can't set it from the client-side request). This is enforced by the browser itself, and not something you can resolve from client-side code.
Quoting from MDN:
For security reasons, browsers restrict cross-origin HTTP requests initiated from within scripts. For example, XMLHttpRequest and the Fetch API follow the same-origin policy. This means that a web application using those APIs can only request HTTP resources from the same domain the application was loaded from unless CORS headers are used.
In this case, it looks like the API is intended to be used from a server, not directly from a browser.
Post a Comment for "How To Overcome Cors Issue With Https://newsapi.org/"