call non-CORS REST APIs over AJAX with CORS proxy server (includes Svelte+Rollup setup)



call non-CORS REST APIs over AJAX with CORS proxy server (includes Svelte+Rollup setup)

call non-CORS REST APIs over AJAX with CORS proxy server (includes Svelte+Rollup setup)

Learn how to run a CORS proxy locally to make AJAX requests to a REST API that is not CORS-ready.

Browsers enforce Same-Origin-Policy on AJAX requests made to origin servers other than where your app is hosted (third-party REST services). CORS (Cross-Origin-Resource-Sharing) allows a third-party server to expose “Access-Control-Allow-Origin” header which tells the browser that it is okay to do so (send AJAX requests to it).

But what if the REST API simply don’t expose that requisite header? We can run a proxy server locally (on the host that is serving your web app) and send the REST/AJAX request to it instead of sending it directly to the third-party server. The proxy server makes the request on your behalf and also adds the CORS headers. And now your AJAX request will be successful.

We do the above for both a basic HTML+JS setup, and then later with a Svelte+Rollup setup.

Also, we show how to use @rollup/plugin-replace to make sure your code works well in both development and production.

Relevant links:
https://joke-api-strict-cors.appspot.com/random_joke
https://www.npmjs.com/package/cors-anywhere
https://github.com/rollup/plugins/tree/master/packages/replace

For questions, post a comment. For business inquiries, email [email protected].

TOC/Index
00:00 Overview of the issue: What is SOP/CORS and what we will do to get around it
02:17 See a live example of the issue
05:00 Start a new project with (basic) HTML+JS and show the CORS error
10:45 AJAX request fails due to missing “Access-Control-Allow-Origin” header
12:15 “cors-anywhere” NPM module
15:30 Fix the CORS issue by running the AJAX request through the CORS proxy
17:30 Success! AJAX works when going through CORS proxy
19:05 Improvement: run CORS proxy from package.json script
20:25 Implement the solution in Svelte + Rollup
29:50 AJAX request from SvelteJS fails due to lack of CORS header. Let’s fix it.
35:00 Implemented CORS proxy in rollup and making request through it
36:00 Add the “replace” plugin to skip the CORS proxy when in production
43:49 Summary and recap

Comments are closed.