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:
$ 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)
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:
- Node.js
- npm - The node package manager
- An Express app
$ 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