From e16bbff161d407dc4bb6c0546fc54b9007e9a2ad Mon Sep 17 00:00:00 2001 From: Mehran Dehghanian Date: Sat, 6 Mar 2021 12:40:40 +0330 Subject: [PATCH] Add 'Using CORS in Express' --- Using-CORS-in-Express.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Using-CORS-in-Express.md diff --git a/Using-CORS-in-Express.md b/Using-CORS-in-Express.md new file mode 100644 index 0000000..624f432 --- /dev/null +++ b/Using-CORS-in-Express.md @@ -0,0 +1,26 @@ +### Using CORS in Express + +Cross-origin resource sharing (CORS) allows AJAX requests to skip the Same-origin policy and access resources from remote hosts. +In this post I will show you how to enable CORS support in Express. I will also provide some tips to handle common use cases that come up when working with Single Page Applications, like exposing HTTP sessions and custom headers. + +### Enabling CORS + +The easiest way to get CORS working in Express is by using the cors npm module. + +You can simply add it as a dependency: +``` +npm install --save cors +And then use it as middleware: +var express = require('express'); +var cors = require('cors'); +var app = express(); +app.use(cors()); +/* your regular routes go here */ +``` + +That’s it. CORS is now enabled. +If you make a request to your app, you will notice a new header being returned: + +`Access-Control-Allow-Origin: *` + +The Access-Control-Allow-Origin header determines which origins are allowed to access server resources over CORS (the * wildcard allows access from any origin).