Home > Enterprise >  Will my website fetch API without CORS error when it is hosted on my web server?
Will my website fetch API without CORS error when it is hosted on my web server?

Time:07-27

I am fetching an API via JavaScript on my localhost. This leads to me having the CORS error:

No 'Access-Control-Allow-Origin' header is present on the requested resource.

Will this still occur when my site is hosted on a my web server, or is it just an issue when I'm hosting via localhost?

CodePudding user response:

If the request is to an external API (not your own site), then the error will continue to occur if the request is made from the client-side.

If the request is to an API on your own site, the error will no longer be present, because browsers allow you to make direct requests to endpoints on the same domain without restrictions.

Even if the API isn't your own, hosting your site on a server can help with these issues because you'll have the option of having your server relay the request to the external API. Clients can't make a request to the external API directly, but they can make a request to an endpoint on your site - and you can set up an endpoint to then make a request to the external API, and relay the response back to the client.

So instead of

client -> external API -> client (doesn't work)

having a server allows you to

client -> your server -> external API -> your server -> client (works)

  • Related