Friday, 7 December 2018

CORS in Express

CORS in Express using TypeScript

A quick walkthrough on configuring CORS in your Express app using TypeScript and the cors middleware.

Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources (e.g. fonts) on a web page to be requested from another domain outside the domain from which the first resource was served.

My use case for CORS is an Angular application that is making REST requests to an API running in Express.js. I’ll be using TypeScript, which will be compiled to ES2015 (ES6) compatible JavaScript that will be executed in Node.js.

Getting Started
We’ll be using Express to serve up some awesome content. I will assume that you have already installed:
  1. Node.js
  2. npm - The node package manager
  3. An Express app
First, let’s install our dependencies. I’ll be using the cors middleware. So, let’s install that package as well as the TypeScript definitions:

$ npm install cors --save

Setting it up
Let’s dive into the server.js file where we will be enabling and configuring CORS in our Express app:

Simple Usage (Enable All CORS Requests)
var express = require('express')

var cors = require('cors')
var app = express()
app.use(cors())
app.get('/products/:id', function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for all origins!'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})


Enable CORS for a Single Route
var express = require('express')
var cors = require('cors')
var app = express()

app.get('/products/:id', cors(), function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for a Single Route'})
})

app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})

Configuring CORS
const corsOptions  = {
  allowedHeaders: ["Origin", "X-Requested-With", "Content-Type", "Accept", "X-Access-Token"],
  credentials: true,
  methods: "GET,HEAD,OPTIONS,PUT,PATCH,POST,DELETE",
  origin: API_URL,
  preflightContinue: false
};


app.get('/products/:id', cors(corsOptions), function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for only example.com.'})
}

0 comments:

Post a Comment

Topics

ADO .Net (2) Ajax (1) Angular Js (17) Angular2 (26) ASP .Net (14) Azure (1) Breeze.js (1) C# (49) CloudComputing (1) CMS (1) CSS (2) Design_Pattern (3) DI (3) Dotnet (21) Entity Framework (3) ExpressJS (4) Html (3) IIS (1) Javascript (6) Jquery (8) Lamda (3) Linq (11) Mongodb (1) MVC (48) NodeJS (7) RDLC (1) Report (1) Sql Server (29) SSIS (3) SSRS (2) UI (1) WCF (13) Web Api (9) Web Service (1) XMl (1)