Chapter 3. Handling CORS requests
This chapter covers
- How to set up the book’s sample application
- What a CORS request looks like from a server’s perspective
- What an origin is
- How to respond to CORS requests using the Access-Control-Allow-Origin header
Suppose you’re the owner of a blog that you programmed yourself. To keep the site scalable, you’ve separated the blog data from the HTML code by introducing an API. The blog page queries the API to load the blog posts, then displays those posts on the page.
As your site becomes more popular, some of your more tech-savvy readers ask if they can use your data to create JavaScript mashups, or embed some of your data on their site by creating a JavaScript widget. They can do this now by screen-scraping the data from your site, but they would be a lot happier if they could plug into the same API you use to load the data for the site.
You love your readers, and think this is a great idea. But when you share your API code with them, it doesn’t work. This is because the browser’s same-origin policy prevents the API request from running from anywhere but your own web application.