how to set up cors() in typescript express
Asked Answered
A

5

13

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>'

Articulate answered 26/12, 2020 at 20:38 Comment(0)
M
4

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

Mindymine answered 5/1, 2021 at 14:13 Comment(1)
Looks like I used your solution back then with adding types for req, res and nextArticulate
A
15

This is because of some ambiguity in the generic typing for the cors library. The easiest way I've found to fix this is simply explicitly specify the request type for the cors method.

import { Request } from "express";
import cors from "cors";

server.use(cors<Request>());
Allhallows answered 26/4, 2022 at 7:36 Comment(1)
Greate it just works fine. thanks a lotCraniate
M
4

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

Mindymine answered 5/1, 2021 at 14:13 Comment(1)
Looks like I used your solution back then with adding types for req, res and nextArticulate
R
1

In my case:

{
  "cors": "^2.8.5",
  "express": "^4.18.1",
  "typescript": "^4.8.4",
}

it works:

import cors = require("cors");
app.use(cors<Request>());
Radnorshire answered 1/10, 2022 at 20:36 Comment(0)
L
0

An update in the same thread,

app.use((cors as (options: cors.CorsOptions) => express.RequestHandler)({}));

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

Loch answered 12/7, 2023 at 18:24 Comment(0)
L
0

All you need to do is install the @types package for cors:

npm i -D @types/cors

Cors doesn't automatically come with its type definitions when you import cors. Thus, you need to install those type definitions using the above npm installation command. Only then, will you have the types for cors and typescript will stop complaining to you. ("-D" saves them as a dev-dependency because types/typescript is only needed in the development environment before transpilation to JS)

Limestone answered 10/7 at 19:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.