'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 setup 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 1:[1]
i found this solution:
Using:
...
"express": "^4.17.1",
"@types/express": "^4.17.9",
...
replace ".use(cors())" for
.use((req, resp, next) => {
next()
}, cors({ maxAge: 84600 }))
Source: https://github.com/DefinitelyTyped/DefinitelyTyped/issues/43909#issuecomment-743156647
Solution 2:[2]
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>());
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Lucas Ferronato |
Solution 2 | DanielG |