Search code examples
node.jstypescriptexpresscors

how to set up cors() in typescript express


In one of my projects, simply this worked:

import cors from "cors";

server.use(cors());

but currently, I am having this lovely typescript warning message in my new project:

  No overload matches this call.
  The last overload gave the following error.
    Argument of type '(req: Request<never, never, never, never>, res: { statusCode?: number | undefined; setHeader(key: string, value: string): any; end(): any; }, next: (err?: any) => any) => void' is not assignable to parameter of type 'RequestHandlerParams<ParamsDictionary, any, any, ParsedQs>'.
      Type '(req: Request<never, never, never, never>, res: { statusCode?: number | undefined; setHeader(key: string, value: string): any; end(): any; }, next: (err?: any) => any) => void' is not assignable to type 'RequestHandler<ParamsDictionary, any, any, ParsedQs>'.
        Types of parameters 'req' and 'req' are incompatible.
          Type 'Request<ParamsDictionary, any, any, ParsedQs>' is not assignable to type 'Request<never, never, never, never>'.
            Type 'ParamsDictionary' is not assignable to type 'never'.ts(2769)

then I tried to set up custom cors middleware and use it:

import { NextFunction ,Request,Response} from 'express';

export const Cors=(req:Request, res:Response, next:NextFunction) => {
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.setHeader(
      "Access-Control-Allow-Methods",
      "OPTIONS, GET, POST, PUT, PATCH, DELETE"
    );
    res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
    if (req.method === "OPTIONS") {
      return res.sendStatus(200);
    }
    next();
  };

   server.use(Cors());

this time i am having another lovely error :

No overload matches this call. The last overload gave the following error. Argument of type 'Response | undefined' is not assignable to parameter of type 'RequestHandlerParams<ParamsDictionary, any, any, ParsedQs>'. Type 'undefined' is not assignable to type 'RequestHandlerParams<ParamsDictionary, any, any, ParsedQs>'


Solution

  • i found this solution:

    Using:

    ...
      "express": "^4.17.1",
      "@types/express": "^4.17.9",
    ...
    

    replace ".use(cors())" for

    app.use((req: Request, res: Response, next: NextFunction) => {
      next();
    }, cors({ maxAge: 84600 }));
    

    Source: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/43909#issuecomment-743156647