Yil*_*maz 10 node.js cors express typescript
在我的一个项目中,这很有效:
import cors from "cors";
server.use(cors());
Run Code Online (Sandbox Code Playgroud)
但目前,我的新项目中出现了这条可爱的打字稿警告消息:
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)
Run Code Online (Sandbox Code Playgroud)
然后我尝试设置自定义 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());
Run Code Online (Sandbox Code Playgroud)
这次我又遇到了另一个可爱的错误:
没有重载与此调用匹配。最后一次超载出现以下错误。'Response | 类型的参数 undefined' 不可分配给类型为 'RequestHandlerParams<ParamsDictionary, any, any, ParsedQs>' 的参数。类型“未定义”不可分配给类型“RequestHandlerParams <ParamsDictionary,any,any,ParsedQs>”
Dan*_*elG 12
这是因为 cors 库的通用类型存在一些歧义。我发现解决此问题的最简单方法就是显式指定该cors方法的请求类型。
import { Request } from "express";
import cors from "cors";
server.use(cors<Request>());
Run Code Online (Sandbox Code Playgroud)
小智 3
我找到了这个解决方案:
使用:
...
"express": "^4.17.1",
"@types/express": "^4.17.9",
...
Run Code Online (Sandbox Code Playgroud)
将“.use(cors())”替换为
app.use((req: Request, res: Response, next: NextFunction) => {
next();
}, cors({ maxAge: 84600 }));
Run Code Online (Sandbox Code Playgroud)
来源:https ://github.com/DefinitelyTyped/DefinitelyTyped/issues/43909#issuecomment-743156647
| 归档时间: |
|
| 查看次数: |
19630 次 |
| 最近记录: |