add cors headers to a http server in typescript

To add CORS headers to a Node.js HTTP server written in TypeScript, you can use a middleware function that intercepts incoming requests and adds the necessary headers.

Here is an example middleware function that adds CORS headers:

index.ts
import { Request, Response, NextFunction } from 'express';

export function corsMiddleware(req: Request, res: Response, next: NextFunction): void {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
  res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  next();
}
387 chars
9 lines

To use this middleware with your HTTP server, simply add it to the chain of middleware functions using the use method of the Express application object:

index.ts
import express from 'express';
import { corsMiddleware } from './middlewares/cors';

const app = express();

app.use(corsMiddleware);
134 chars
7 lines

This will add the CORS headers to all requests handled by your server. Note that you can adjust the values of the headers according to your specific needs.

gistlibby LogSnag