Skip to content

Instantly share code, notes, and snippets.

@adjeim
Last active March 20, 2024 07:37
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save adjeim/a2ddb5214c92ce5d708fb0a3d6f073f6 to your computer and use it in GitHub Desktop.
Save adjeim/a2ddb5214c92ce5d708fb0a3d6f073f6 to your computer and use it in GitHub Desktop.
CORS Cheat Sheet for Express + TypeScript
  1. Install cors package and its TypeScript types:
npm install cors
npm install --save-dev @types/cors
  1. Update the entry point of your Express app to allow your server to use cors middleware. Configure your CORS options with the origins you would like to allow.
import express from 'express';
import cors from 'cors';

const app = express();

// Add a list of allowed origins.
// If you have more origins you would like to add, you can add them to the array below.
const allowedOrigins = ['http://localhost:3000'];

const options: cors.CorsOptions = {
  origin: allowedOrigins
};

// Then pass these options to cors:
app.use(cors(options));

app.use(express.json());


app.listen(5000, () => {
  console.log('Express server listening on port 5000');
});
@SchoolyB
Copy link

SchoolyB commented May 6, 2023

THANK YOU 👍

@hasael-web
Copy link

thank you

@Demnu
Copy link

Demnu commented Nov 5, 2023

perfect! thankyou

@DhruvSavaj
Copy link

Thanks, I resolved the error but CORS is not preventing it properly, do you have any idea?

I have allowed only one origin "http://localhost:3000", and I am testing with the "http://localhost:450" URL from Postman, by changing "Origin".

Here is my sample cURL, localhost:8936 is my API endpoint

curl --location 'localhost:8936' \ --header 'Origin: localhost:450'

It is still getting a 200 OK response.

@socx
Copy link

socx commented Mar 20, 2024

Very useful! Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment