add cors headers to a http server with a specific origin and methods in typescript

To add CORS headers to a HTTP server with a specific origin and methods in TypeScript, you can use the cors middleware package which allows you to easily configure CORS settings for your HTTP server. Here's an example of how to use it in your code:

index.ts
import express from 'express';
import cors from 'cors';

const app = express();

const corsOptions = {
  origin: 'http://example.com', // specify the allowed origin domain
  methods: ['GET', 'PUT', 'POST'] // specify the allowed HTTP methods
};

app.use(cors(corsOptions));
// add more middleware and route handlers here
321 chars
13 lines

In the code above, we first imported the express and cors packages. We then created an instance of the Express application with express(). Next, we created a configuration object corsOptions with the allowed origin and methods. Finally, we used the cors middleware function and passed in corsOptions as an argument to enable CORS for our server.

With this configuration, our server will only allow HTTP requests from http://example.com and the allowed methods are GET, PUT, and POST. You can adjust these settings to meet your specific needs.

gistlibby LogSnag