Testing CORS Support in Express Gateway v1.2 : Part 1

Author: Shweeta A Mane

Express Gateway
Express Gateway is an open source API Gateway built on top of the Express framework. You may be familiar with the Express framework already, since it is the most popular framework for developing web applications in Node.js. Express Gateway is in essence an Express.js application that exposes back-end services as APIs, and configures the request-response pipeline for accessing API end-points using one or more Express middleware components. That makes Express Gateway lightweight, easy to set-up and highly configurable.

What is CORS ?
Cross-Origin Resource Sharing (CORS) comes into picture when a script running on a web-page hosted on Server A tries to access resources hosted on another server, Server B on a different network domain. This is a commonly encountered scenario. An online news portal may access and display stock quotes from a web application hosted at a stock exchange, weather conditions from a web-application hosted at a meteorological department, and selected tweets.

But ordinarily, the client browser will not allow a web-page to run a script that accesses a third-party resource (from a separate network domain, for example the stock exchange domain). Nor will the third-party web-application allow access from a script hosted on a separate domain (for example, the domain on which the news portal is hosted), unless explicitly configured to do so.

Why should an API Gateway support CORS?
An API Gateway is essentially a server hosted on a certain network domain. API end-points may be accessed by external programs (often written using an SDK for the exposed APIs). But API end-points exposed by the Gateway may also be accessed from web-pages hosted on a separate domain. Hence, an API Gateway should allow an administrator to enable CORS on one or more exposed APIs.

Express Gateway supports CORS Functionality
Express Gateway allows us to configure a 'pipeline' for each API endpoint. A pipeline consists of 'policies' which are like request handlers that each request from an external client must pass through. Under the hood, a 'policy' is an Express middleware component.

To enable CORS on a certain API endpoint, all we need is to insert a policy called 'cors' into the pipeline for that endpoint.

If you have created an Express Gateway using the command eg gateway create and chosen a 'basic' pipeline for your API end-points, then the 'cors' policy is already installed for you. You just need to place it in your pipeline. Refer to an example configuration file (config/gateway.config.yml) below. We will explain it in more detail in the next part of this blog.

cors config

Test Set-up
In order to test out CORS support in Express Gateway, we will use the following set-up: A VirtualBox Virtual Machine with Ubuntu desktop 16.04 installed.