Chapter 2. Making CORS requests

 

This chapter covers

  • Which browsers support CORS
  • How to use the XMLHttpRequest object to make CORS requests
  • How to use the XDomainRequest object in Internet Explorer 8 and 9
  • How to load cross-origin images in a canvas element
  • How to make CORS requests from jQuery

A CORS request consists of two sides: the client making the request, and the server receiving the request. On the client side, the developer writes JavaScript code to send the request to the server. The server responds to the request by setting special CORS-specific headers to indicate that the cross-origin request is allowed. Without both the client’s and the server’s participation, the CORS request will fail.

This chapter focuses on how to make CORS requests from JavaScript. It assumes you have an existing CORS-enabled API (such as the Flickr API, the GitHub API, or your own API) to make requests to (if you don’t have an existing CORS-enabled API, don’t worry. Part 2 looks at how to set one up). The chapter starts by defining what a cross-origin request is and which browsers support it. It then covers the main ways to make CORS requests, including the XMLHttpRequest and XDomainRequest objects. Next it looks at how the HTML5 <canvas> element uses CORS to load images. It ends with a look at jQuery support for CORS. The server-side details of CORS will be covered in chapter 3.

2.1. What is a cross-origin request?

2.2. Browser support for CORS

2.3. Using the XMLHttpRequest object

2.4. XDomainRequest object in Internet Explorer 8 and 9

2.5. Canvas and cross-origin images

2.6. CORS requests from jQuery

2.7. Summary

sitemap