在我的一个项目中,这很有效:
import cors from "cors";
server.use(cors());
但目前,我的新项目中出现了这条可爱的打字稿警告消息:
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)
然后我尝试设置自定义 cors 中间件并使用它:
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());
这次我又犯了一个可爱的错误:
没有重载与此调用匹配。
最后一次超载出现以下错误。
'Response | 类型的参数undefined' 不可分配给'RequestHandlerParams
这是因为 cors 库的通用类型存在一些歧义。我发现解决此问题的最简单方法就是显式指定
cors
方法的请求类型。
import { Request } from "express";
import cors from "cors";
server.use(cors<Request>());
我找到了这个解决方案:
使用:
...
"express": "^4.17.1",
"@types/express": "^4.17.9",
...
将“.use(cors())”替换为
app.use((req: Request, res: Response, next: NextFunction) => {
next();
}, cors({ maxAge: 84600 }));
来源:https://github.com/DefinitelyTyped/DefinitelyTyped/issues/43909#issuecomment-743156647
就我而言:
{
"cors": "^2.8.5",
"express": "^4.18.1",
"typescript": "^4.8.4",
}
它有效:
import cors = require("cors");
app.use(cors<Request>());
同一线程中的更新,
app.use((cors as (options: cors.CorsOptions) => express.RequestHandler)({}));
https://github.com/DefinitelyTyped/DefinitelyTyped/issues/43909#issuecomment-1168194740
您需要做的就是安装 cors 的 @types 包:
npm i -D @types/cors
当您导入 cors 时,Cors 不会自动附带其类型定义。因此,您需要使用上述 npm 安装命令来安装这些类型定义。只有这样,你才会拥有 cors 的类型,并且 typescript 将停止向你抱怨。 (“-D”将它们保存为开发依赖项,因为类型/打字稿仅在转换为 JS 之前在开发环境中需要)