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

To add CORS headers to a HTTP server with a specific origin in TypeScript, we can use the cors middleware package.

First, install the package using npm:

npm install cors
17 chars
2 lines

Then, create a new server using the http module and define the CORS options object with the desired origin:

index.ts
import * as http from 'http';
import * as cors from 'cors';

const PORT = 3000;
const ORIGIN_URL = 'https://example.com';

const corsOptions = {
  origin: ORIGIN_URL
};

const server = http.createServer();
206 chars
12 lines

Next, install the cors middleware to your server and start listening:

index.ts
server.on('request', cors(corsOptions), (req, res) => {
  // handle HTTP requests here
});

server.listen(PORT, () => {
  console.log(`Server running at http://localhost:${PORT}`);
});
185 chars
8 lines

With this code, your server will now only accept requests from the specified origin.

gistlibby LogSnag