CORS in Action
eBook - ePub

CORS in Action

Creating and consuming cross-origin APIs

Monsur Hossain

Condividi libro
  1. 240 pagine
  2. English
  3. ePUB (disponibile sull'app)
  4. Disponibile su iOS e Android
eBook - ePub

CORS in Action

Creating and consuming cross-origin APIs

Monsur Hossain

Dettagli del libro
Anteprima del libro
Indice dei contenuti
Citazioni

Informazioni sul libro

Summary CORS in Action introduces Cross-Origin Resource Sharing (CORS) from both the server and the client perspective. It starts with the basics: how to make CORS requests and how to implement CORS on the server. It then explores key details such as performance, debugging, and security. API authors will learn how CORS opens their APIs to a wider range of users. JavaScript developers will find valuable techniques for building rich web apps that can take advantage of APIs hosted anywhere. The techniques described in this book are especially applicable to mobile environments, where browsers are guaranteed to support CORS. Purchase of the print book includes a free eBook in PDF, Kindle, and ePub formats from Manning Publications. About the Book Suppose you need to share some JSON data with another application or service. If everything is hosted on one domain, it's a snap. But if the data is on another domain, the browser's "same-origin" policy stops you cold. CORS is a new web standard that enables safe cross-domain access without complex server-side code. Mastering CORS makes it possible for web and mobile applications to share data simply and securely. CORS in Action introduces CORS from both the server and the client perspective. It starts with making and enabling CORS requests and then explores performance, debugging, and security. You'll learn to build apps that can take advantage of APIs hosted anywhere and how to write APIs that expand your products to a wider range of users. For web developers comfortable with JavaScript. No experience with CORS is assumed. What's Inside

  • CORS from the ground up
  • Serving and consuming cross-domain data
  • Best practices for building CORS APIs
  • When to use CORS alternatives like JSON-P and proxies


About the Author Monsur Hossain is an engineer at Google who has worked on API-related projects such as the Google JavaScript Client, the APIs Discovery Service, and CORS support for Google APIs. Table of Contents
PART 1 INTRODUCING CORS

  • The Core of CORS
  • Making CORS requests
  • PART 2 CORS ON THE SERVER
  • Handling CORS requests
  • Handling preflight requests
  • Cookies and response headers
  • Best practices
  • PART 3 DEBUGGING CORS REQUESTS
  • Debugging CORS requests

  • APPENDIXES
  • CORS reference
  • Configuring your environment
  • What is CSRF?
  • Other cross-origin techniques

Domande frequenti

Come faccio ad annullare l'abbonamento?
È semplicissimo: basta accedere alla sezione Account nelle Impostazioni e cliccare su "Annulla abbonamento". Dopo la cancellazione, l'abbonamento rimarrà attivo per il periodo rimanente già pagato. Per maggiori informazioni, clicca qui
È possibile scaricare libri? Se sì, come?
Al momento è possibile scaricare tramite l'app tutti i nostri libri ePub mobile-friendly. Anche la maggior parte dei nostri PDF è scaricabile e stiamo lavorando per rendere disponibile quanto prima il download di tutti gli altri file. Per maggiori informazioni, clicca qui
Che differenza c'è tra i piani?
Entrambi i piani ti danno accesso illimitato alla libreria e a tutte le funzionalità di Perlego. Le uniche differenze sono il prezzo e il periodo di abbonamento: con il piano annuale risparmierai circa il 30% rispetto a 12 rate con quello mensile.
Cos'è Perlego?
Perlego è un servizio di abbonamento a testi accademici, che ti permette di accedere a un'intera libreria online a un prezzo inferiore rispetto a quello che pagheresti per acquistare un singolo libro al mese. Con oltre 1 milione di testi suddivisi in più di 1.000 categorie, troverai sicuramente ciò che fa per te! Per maggiori informazioni, clicca qui.
Perlego supporta la sintesi vocale?
Cerca l'icona Sintesi vocale nel prossimo libro che leggerai per verificare se è possibile riprodurre l'audio. Questo strumento permette di leggere il testo a voce alta, evidenziandolo man mano che la lettura procede. Puoi aumentare o diminuire la velocità della sintesi vocale, oppure sospendere la riproduzione. Per maggiori informazioni, clicca qui.
CORS in Action è disponibile online in formato PDF/ePub?
Sì, puoi accedere a CORS in Action di Monsur Hossain in formato PDF e/o ePub, così come ad altri libri molto apprezzati nelle sezioni relative a Informatica e Programmazione web. Scopri oltre 1 milione di libri disponibili nel nostro catalogo.

Informazioni

Editore
Manning
Anno
2014
ISBN
9781638353256

Part 1. Introducing CORS

Cross-Origin Resource Sharing (CORS) enables web clients to make HTTP requests to servers hosted on different origins. CORS is a unique web technology in that it has both a server-side and a client-side component. The server-side component configures which types of cross-origin requests are allowed, while the client-side component controls how cross-origin requests are made.
Part 1 focuses on the client-side component of CORS. Chapter 1 is an introduction to CORS, how it works, and its benefits. It also gives a taste of what CORS looks like by introducing a sample application that makes CORS requests to the Flickr API.
Chapter 2 dives deeper into this sample application to show how the client-side component of CORS works. It starts by looking at how the browser’s XMLHttpRequest object (which is already familiar to any developer making same-origin requests) can be used to make cross-origin requests. Then, it turns to Internet Explorer 8 and Internet Explorer 9, which support a subset of CORS via the XDomainRequest object. Next, it looks at other places where CORS requests turn up, such as the canvas element. The chapter concludes by looking at how CORS requests can be made from jQuery.

Chapter 1. The Core of CORS

This chapter covers
  • Which issues CORS solves
  • How a CORS request works
  • The benefits of CORS
Suppose you’re building a web mashup to load photos from the New York Public Library’s (NYPL) Flickr page and display them on your own page. What would the code look like? You could start with an HTML page to display the photos, add JavaScript code to load the photos from the Flickr page, and display them on the page. Pretty straightforward, right?
But if you were to run this code in the browser, it wouldn’t work because the browser’s same-origin policy limits client code from making HTTP requests to different origins. This means that a web page running from your desktop or web server can’t make an HTTP request to Flickr.com.
Cross-Origin Resource Sharing, or CORS, was built to help solve this issue. Before CORS, developers would need to go to great lengths to access APIs from JavaScript clients in the browser. CORS enables cross-origin requests in a safe, standard manner. From a client’s perspective, CORS is awesome because it opens up a new world of APIs that previously wasn’t available to browser JavaScript. From a server’s perspective, CORS is awesome because it allows the server to open up its APIs to a new world of users.
This chapter gives an overview of what CORS is and how it’s used. It begins by reviewing CORS’s features and benefits. It then walks through the code to make a CORS request.

1.1. What is CORS?

CORS is simply a way of making HTTP requests from one place to another. This is a trivial thing in other programming languages. But it’s difficult to do in client-side JavaScript, because for years the browser’s same-origin policy has explicitly prevented these types of requests.
This may make CORS sound like a contradiction. How can CORS allow cross-origin requests if the same-origin policy explicitly forbids them? The key is that CORS puts servers firmly in charge of who can make requests, and what type of requests are allowed. A server has the choice to open up its API to all clients, open it up to a small number of clients, or prevent access to all clients.
So if browsers enforce a same-origin policy, how does CORS work? The secret lies in the request and response headers. The browser and the server use HTTP headers to communicate how cross-origin requests behave. Using the response headers, the server can indicate which clients can access the API, which HTTP methods or HTTP headers are allowed, and whether cookies are allowed in the request.
Figure 1.1 shows what an end-to-end CORS request to the Flickr API looks like.
Figure 1.1. End-to-end CORS request flow
Here is a simplified look at the steps to making a CORS request (there are a few more nuances to some CORS requests, which we’ll cover in later chapters):
1. The CORS request is initiated by the JavaScript client code.
2. The browser includes additional HTTP headers on the request before sending the request to the server.
3. The server includes HTTP headers in the response that indicate whether the request is allowed.
4. If the request is allowed, the browser sends the response to the client code.
If the headers returned by the server don’t exist, or aren’t what the browser expects, the response is rejected and the client can’t view the response. In this way, browsers can still enforce the same-origin policy on servers that don’t allow cross-origin requests. Now that you have a sense of what CORS is, let’s turn our attention to making a CORS request.

1.2. CORS by example

Let’s demonstrate how CORS works by building a Flickr sample app. Figure 1.2 shows the app, which loads photos from the NYPL’s Flickr site and displays them on the page.
Figure 1.2. Loading photos from Flickr using CORS
The following listing shows the code behind this sample.
Listing 1.1. Making a CORS request
Note
If you’d like to run this sample in your browser, you’ll need to obtain an API key from Flickr and substitute it for the <YOUR API KEY HERE> string in the code. You can obtain an API key at www.flickr.com/services/apps/create/.
If you save this code to an HTML file (and set the API key as mentioned in the preceding note) and then open that file in your browser, you should see a bunch of photo...

Indice dei contenuti