Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typescript/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 如何在typescript express中设置cors()_Node.js_Typescript_Express_Cors - Fatal编程技术网

Node.js 如何在typescript express中设置cors()

Node.js 如何在typescript express中设置cors(),node.js,typescript,express,cors,Node.js,Typescript,Express,Cors,在我的一个项目中,这很简单: import cors from "cors"; server.use(cors()); 但目前我的新项目中有一条可爱的typescript警告信息: No overload matches this call. The last overload gave the following error. Argument of type '(req: Request<never, never, never, never>

在我的一个项目中,这很简单:

import cors from "cors";

server.use(cors());
但目前我的新项目中有一条可爱的typescript警告信息:

  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)
这次我又犯了一个可爱的错误:

没有与此调用匹配的重载。 上一次重载导致以下错误。 “Response | undefined”类型的参数不能分配给“RequestHandlerParams”类型的参数。 类型“undefined”不能分配给类型“RequestHandlerParams”

我找到了这个解决方案:

使用:

。。。
“快车”:“^4.17.1”,
“@types/express”:“^4.17.9”,
...
将“.use(cors())”替换为

。使用((请求、响应、下一步)=>{
下一个()
},cors({maxAge:84600}))
资料来源:

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());