Book Image

CORS Essentials

By : Rajesh Gunasundaram
Book Image

CORS Essentials

By: Rajesh Gunasundaram

Overview of this book

This book explains how to use CORS, including specific implementations for platforms such as Drupal, WordPress, IIS Server, ASP.NET, JBoss, Windows Azure, and Salesforce, as well as how to use CORS in the Cloud on Amazon AWS, YouTube, Mulesoft, and others. It examines limitations, security risks, and alternatives to CORS. It explores the W3C Specification and major developer documentation sources about CORS. It attempts to predict what kinds of extension to the CORS specification, or completely new techniques, will come in the future to address the limitations of CORS Web developers will learn how to share code and assets across domains with CORS. They will learn a variety of techniques that are rather similar in their method and syntax. The book is organized by similar types of framework and application, so it can be used as a reference. Developers will learn about special cases, such as when a proxy is necessary. And they will learn about some alternative techniques that achieve similar goals, and when they may be preferable to using CORS
Table of Contents (15 chapters)
CORS Essentials
Credits
About the Authors
www.PacktPub.com
Customer Feedback
Preface
Index

CORS in Express.js


The following code adds the Access-Control-Allow-Origin and Access-Control-Allow-Headers headers globally to all requests on all routes in an Express.js application. A route is a path in the Express.js application, for example, /user for a user page. app.all sets the configuration for all routes in the application. Specific HTTP requests such as GET or POST are handled by app.get and app.post:

app.all('*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  next();
});

app.get('/', function(req, res, next) {
  // Handle GET for this route
});

app.post('/', function(req, res, next) {
// Handle the POST for this route
});

For better security, consider limiting the allowed origin to a single domain, or adding some additional code to validate or limit the domain(s) that are allowed. Also, consider limiting sending the headers only to routes that require CORS by replacing app.all with...