NodeJS 如何在typescript express中设置cors()

4dc9hkyq  于 2022-11-22  发布在  Node.js
关注(0)|答案(3)|浏览(150)

在我的一个项目中,简单地这样做就成功了:

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”类型的参数|“未定义”不能赋给类型“RequestHandlerParams”的参数。类型“未定义”不能赋给类型“RequestHandlerParams”

6vl6ewon

6vl6ewon1#

这是因为cors库的泛型类型中存在一些不明确的地方,我发现解决这个问题的最简单的方法就是显式地指定cors方法的请求类型。

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

server.use(cors<Request>());
t3irkdon

t3irkdon2#

我找到了这个解决方案:
使用:

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

将“.use(cors())”替换为

.use((req, resp, next) => {
    next()
  }, cors({ maxAge: 84600 }))

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

62lalag4

62lalag43#

在我的例子中:

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

它的工作原理是:
第一次

相关问题