CORS in Action
eBook - ePub

CORS in Action

Creating and consuming cross-origin APIs

Monsur Hossain

Compartir libro
  1. 240 páginas
  2. English
  3. ePUB (apto para móviles)
  4. Disponible en iOS y Android
eBook - ePub

CORS in Action

Creating and consuming cross-origin APIs

Monsur Hossain

Detalles del libro
Vista previa del libro
Índice
Citas

Información del 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

Preguntas frecuentes

¿Cómo cancelo mi suscripción?
Simplemente, dirígete a la sección ajustes de la cuenta y haz clic en «Cancelar suscripción». Así de sencillo. Después de cancelar tu suscripción, esta permanecerá activa el tiempo restante que hayas pagado. Obtén más información aquí.
¿Cómo descargo los libros?
Por el momento, todos nuestros libros ePub adaptables a dispositivos móviles se pueden descargar a través de la aplicación. La mayor parte de nuestros PDF también se puede descargar y ya estamos trabajando para que el resto también sea descargable. Obtén más información aquí.
¿En qué se diferencian los planes de precios?
Ambos planes te permiten acceder por completo a la biblioteca y a todas las funciones de Perlego. Las únicas diferencias son el precio y el período de suscripción: con el plan anual ahorrarás en torno a un 30 % en comparación con 12 meses de un plan mensual.
¿Qué es Perlego?
Somos un servicio de suscripción de libros de texto en línea que te permite acceder a toda una biblioteca en línea por menos de lo que cuesta un libro al mes. Con más de un millón de libros sobre más de 1000 categorías, ¡tenemos todo lo que necesitas! Obtén más información aquí.
¿Perlego ofrece la función de texto a voz?
Busca el símbolo de lectura en voz alta en tu próximo libro para ver si puedes escucharlo. La herramienta de lectura en voz alta lee el texto en voz alta por ti, resaltando el texto a medida que se lee. Puedes pausarla, acelerarla y ralentizarla. Obtén más información aquí.
¿Es CORS in Action un PDF/ePUB en línea?
Sí, puedes acceder a CORS in Action de Monsur Hossain en formato PDF o ePUB, así como a otros libros populares de Informatica y Programmazione web. Tenemos más de un millón de libros disponibles en nuestro catálogo para que explores.

Información

Editorial
Manning
Año
2014
ISBN
9781638353256
Categoría
Informatica

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...

Índice