@ts-stack/cors
TypeScript icon, indicating that this package has built-in type declarations

1.4.2 • Public • Published

@ts-stack/cors

CORS is a node.js package writen in TypeScript for providing a sync middleware that can be used to enable CORS with various options.

This package is a fork of express/cors module from this state.

Installation

npm install @ts-stack/cors

Usage

Simple Usage (Enable CORS Requests to https://example.com)

import http from 'http';
import { cors, mergeOptions } from '@ts-stack/cors';

const hostname = '127.0.0.1';
const port = 3000;
const corsOptions = mergeOptions({ origin: 'https://example.com' });

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  const headersSent = cors(req, res, corsOptions);
  if (headersSent) {
    return;
  }
  res.setHeader('Content-Type', 'text/plain');
  res.end('This is CORS-enabled for https://example.com!');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

Enabling CORS Preflight

Certain CORS requests are considered 'complex' and require an initial OPTIONS request (called the preflight request). An example of a 'complex' CORS request is one that uses an HTTP verb other than GET/HEAD/POST (such as DELETE) or that uses custom headers. To enable preflighting, you must add a new OPTIONS handler for the route you want to support.

The default configuration

The default configuration is the equivalent of:

{
  "origin": "*",
  "allowedMethods": "GET,HEAD,PUT,PATCH,POST,DELETE",
  "preflightContinue": false,
  "optionsSuccessStatus": 204
}

For details on the effect of each CORS header, read this article on web.dev.

Dependents (1)

Package Sidebar

Install

npm i @ts-stack/cors

Weekly Downloads

14,381

Version

1.4.2

License

MIT

Unpacked Size

39 kB

Total Files

25

Last publish

Collaborators

  • ktretiak