opusdev/vector-similarity-api
1
1# cors2 3[![NPM Version][npm-image]][npm-url]4[![NPM Downloads][downloads-image]][downloads-url]5[![Build Status][github-actions-ci-image]][github-actions-ci-url]6[![Test Coverage][coveralls-image]][coveralls-url]7 8CORS is a [Node.js](https://nodejs.org/en/) middleware for [Express](https://expressjs.com/)/[Connect](https://github.com/senchalabs/connect) that sets [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS) response headers. These headers tell browsers which origins can read responses from your server.9 10> [!IMPORTANT]11> **How CORS Works:** This package sets response headers—it doesn't block requests. CORS is enforced by browsers: they check the headers and decide if JavaScript can read the response. Non-browser clients (curl, Postman, other servers) ignore CORS entirely. See the [MDN CORS guide](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS) for details.12 13* [Installation](#installation)14* [Usage](#usage)15 * [Simple Usage](#simple-usage-enable-all-cors-requests)16 * [Enable CORS for a Single Route](#enable-cors-for-a-single-route)17 * [Configuring CORS](#configuring-cors)18 * [Configuring CORS w/ Dynamic Origin](#configuring-cors-w-dynamic-origin)19 * [Enabling CORS Pre-Flight](#enabling-cors-pre-flight)20 * [Customizing CORS Settings Dynamically per Request](#customizing-cors-settings-dynamically-per-request)21* [Configuration Options](#configuration-options)22* [Common Misconceptions](#common-misconceptions)23* [License](#license)24* [Original Author](#original-author)25 26## Installation27 28This is a [Node.js](https://nodejs.org/en/) module available through the29[npm registry](https://www.npmjs.com/). Installation is done using the30[`npm install` command](https://docs.npmjs.com/downloading-and-installing-packages-locally):31 32```sh33$ npm install cors34```35 36## Usage37 38### Simple Usage (Enable *All* CORS Requests)39 40```javascript41var express = require('express')42var cors = require('cors')43var app = express()44 45// Adds headers: Access-Control-Allow-Origin: *46app.use(cors())47 48app.get('/products/:id', function (req, res, next) {49 res.json({msg: 'Hello'})50})51 52app.listen(80, function () {53 console.log('web server listening on port 80')54})55```56 57### Enable CORS for a Single Route58 59```javascript60var express = require('express')61var cors = require('cors')62var app = express()63 64// Adds headers: Access-Control-Allow-Origin: *65app.get('/products/:id', cors(), function (req, res, next) {66 res.json({msg: 'Hello'})67})68 69app.listen(80, function () {70 console.log('web server listening on port 80')71})72```73 74### Configuring CORS75 76See the [configuration options](#configuration-options) for details.77 78```javascript79var express = require('express')80var cors = require('cors')81var app = express()82 83var corsOptions = {84 origin: 'http://example.com',85 optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 20486}87 88// Adds headers: Access-Control-Allow-Origin: http://example.com, Vary: Origin89app.get('/products/:id', cors(corsOptions), function (req, res, next) {90 res.json({msg: 'Hello'})91})92 93app.listen(80, function () {94 console.log('web server listening on port 80')95})96```97 98### Configuring CORS w/ Dynamic Origin99 100This module supports validating the origin dynamically using a function provided101to the `origin` option. This function will be passed a string that is the origin102(or `undefined` if the request has no origin), and a `callback` with the signature103`callback(error, origin)`.104 105The `origin` argument to the callback can be any value allowed for the `origin`106option of the middleware, except a function. See the107[configuration options](#configuration-options) section for more information on all108the possible value types.109 110This function is designed to allow the dynamic loading of allowed origin(s) from111a backing datasource, like a database.112 113```javascript114var express = require('express')115var cors = require('cors')116var app = express()117 118var corsOptions = {119 origin: function (origin, callback) {120 // db.loadOrigins is an example call to load121 // a list of origins from a backing database122 db.loadOrigins(function (error, origins) {123 callback(error, origins)124 })125 }126}127 128// Adds headers: Access-Control-Allow-Origin: <matched origin>, Vary: Origin129app.get('/products/:id', cors(corsOptions), function (req, res, next) {130 res.json({msg: 'Hello'})131})132 133app.listen(80, function () {134 console.log('web server listening on port 80')135})136```137 138### Enabling CORS Pre-Flight139 140Certain CORS requests are considered 'complex' and require an initial141`OPTIONS` request (called the "pre-flight request"). An example of a142'complex' CORS request is one that uses an HTTP verb other than143GET/HEAD/POST (such as DELETE) or that uses custom headers. To enable144pre-flighting, you must add a new OPTIONS handler for the route you want145to support:146 147```javascript148var express = require('express')149var cors = require('cors')150var app = express()151 152app.options('/products/:id', cors()) // preflight for DELETE153app.del('/products/:id', cors(), function (req, res, next) {154 res.json({msg: 'Hello'})155})156 157app.listen(80, function () {158 console.log('web server listening on port 80')159})160```161 162You can also enable pre-flight across-the-board like so:163 164```javascript165app.options('*', cors()) // include before other routes166```167 168NOTE: When using this middleware as an application level middleware (for169example, `app.use(cors())`), pre-flight requests are already handled for all170routes.171 172### Customizing CORS Settings Dynamically per Request173 174For APIs that require different CORS configurations for specific routes or requests, you can dynamically generate CORS options based on the incoming request. The `cors` middleware allows you to achieve this by passing a function instead of static options. This function is called for each incoming request and must use the callback pattern to return the appropriate CORS options.175 176The function accepts:1771. **`req`**: 178 - The incoming request object.179 1802. **`callback(error, corsOptions)`**: 181 - A function used to return the computed CORS options.182 - **Arguments**:183 - **`error`**: Pass `null` if there’s no error, or an error object to indicate a failure.184 - **`corsOptions`**: An object specifying the CORS policy for the current request.185 186Here’s an example that handles both public routes and restricted, credential-sensitive routes:187 188```javascript189var dynamicCorsOptions = function(req, callback) {190 var corsOptions;191 if (req.path.startsWith('/auth/connect/')) {192 // Access-Control-Allow-Origin: http://mydomain.com, Access-Control-Allow-Credentials: true, Vary: Origin193 corsOptions = {194 origin: 'http://mydomain.com',195 credentials: true196 };197 } else {198 // Access-Control-Allow-Origin: *199 corsOptions = { origin: '*' };200 }201 callback(null, corsOptions);202};203 204app.use(cors(dynamicCorsOptions));205 206app.get('/auth/connect/twitter', function (req, res) {207 res.send('Hello');208});209 210app.get('/public', function (req, res) {211 res.send('Hello');212});213 214app.listen(80, function () {215 console.log('web server listening on port 80')216})217```218 219## Configuration Options220 221* `origin`: Configures the **Access-Control-Allow-Origin** CORS header. Possible values:222 - `Boolean` - set `origin` to `true` to reflect the [request origin](https://datatracker.ietf.org/doc/html/draft-abarth-origin-09), as defined by `req.header('Origin')`, or set it to `false` to disable CORS.223 - `String` - set `origin` to a specific origin. For example, if you set it to224 - `"http://example.com"` only requests from "http://example.com" will be allowed.225 - `"*"` for all domains to be allowed. 226 - `RegExp` - set `origin` to a regular expression pattern which will be used to test the request origin. If it's a match, the request origin will be reflected. For example the pattern `/example\.com$/` will reflect any request that is coming from an origin ending with "example.com".227 - `Array` - set `origin` to an array of valid origins. Each origin can be a `String` or a `RegExp`. For example `["http://example1.com", /\.example2\.com$/]` will accept any request from "http://example1.com" or from a subdomain of "example2.com".228 - `Function` - set `origin` to a function implementing some custom logic. The function takes the request origin as the first parameter and a callback (called as `callback(err, origin)`, where `origin` is a non-function value of the `origin` option) as the second.229* `methods`: Configures the **Access-Control-Allow-Methods** CORS header. Expects a comma-delimited string (ex: 'GET,PUT,POST') or an array (ex: `['GET', 'PUT', 'POST']`).230* `allowedHeaders`: Configures the **Access-Control-Allow-Headers** CORS header. Expects a comma-delimited string (ex: 'Content-Type,Authorization') or an array (ex: `['Content-Type', 'Authorization']`). If not specified, defaults to reflecting the headers specified in the request's **Access-Control-Request-Headers** header.231* `exposedHeaders`: Configures the **Access-Control-Expose-Headers** CORS header. Expects a comma-delimited string (ex: 'Content-Range,X-Content-Range') or an array (ex: `['Content-Range', 'X-Content-Range']`). If not specified, no custom headers are exposed.232* `credentials`: Configures the **Access-Control-Allow-Credentials** CORS header. Set to `true` to pass the header, otherwise it is omitted.233* `maxAge`: Configures the **Access-Control-Max-Age** CORS header. Set to an integer to pass the header, otherwise it is omitted.234* `preflightContinue`: Pass the CORS preflight response to the next handler.235* `optionsSuccessStatus`: Provides a status code to use for successful `OPTIONS` requests, since some legacy browsers (IE11, various SmartTVs) choke on `204`.236 237The default configuration is the equivalent of:238 239```json240{241 "origin": "*",242 "methods": "GET,HEAD,PUT,PATCH,POST,DELETE",243 "preflightContinue": false,244 "optionsSuccessStatus": 204245}246```247 248## Common Misconceptions249 250### "CORS blocks requests from disallowed origins"251 252**No.** Your server receives and processes every request. CORS headers tell the browser whether JavaScript can read the response—not whether the request is allowed.253 254### "CORS protects my API from unauthorized access"255 256**No.** CORS is not access control. Any HTTP client (curl, Postman, another server) can call your API regardless of CORS settings. Use authentication and authorization to protect your API.257 258### "Setting `origin: 'http://example.com'` means only that domain can access my server"259 260**No.** It means browsers will only let JavaScript from that origin read responses. The server still responds to all requests.261 262## License263 264[MIT License](http://www.opensource.org/licenses/mit-license.php)265 266## Original Author267 268[Troy Goode](https://github.com/TroyGoode) ([troygoode@gmail.com](mailto:troygoode@gmail.com))269 270[coveralls-image]: https://img.shields.io/coveralls/expressjs/cors/master.svg271[coveralls-url]: https://coveralls.io/r/expressjs/cors?branch=master272[downloads-image]: https://img.shields.io/npm/dm/cors.svg273[downloads-url]: https://npmjs.com/package/cors274[github-actions-ci-image]: https://img.shields.io/github/actions/workflow/status/expressjs/cors/ci.yml?branch=master&label=ci275[github-actions-ci-url]: https://github.com/expressjs/cors?query=workflow%3Aci276[npm-image]: https://img.shields.io/npm/v/cors.svg277[npm-url]: https://npmjs.com/package/cors278 