如何在 typescript express 中设置 cors()

Posted

技术标签:

【中文标题】如何在 typescript express 中设置 cors()【英文标题】:how to set up cors() in typescript express 【发布时间】:2021-04-04 05:10:19 【问题描述】:

在我的一个项目中,这很有效:

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

这次我又犯了一个可爱的错误:

没有重载匹配这个调用。 最后一个重载给出了以下错误。 '响应 | 类型的参数undefined' 不可分配给“RequestHandlerParams”类型的参数。 类型 'undefined' 不可分配给类型 'RequestHandlerParams'

【问题讨论】:

【参考方案1】:

我找到了这个解决方案:

使用:

...
  "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

【讨论】:

【参考方案2】:

来自express official documentation:

对于所有 cors 请求,请执行以下操作

var express = require('express')
var cors = require('cors')
var app = express()

app.use(cors())

app.get('/products/:id', function (req, res, next) 
  res.json(msg: 'This is CORS-enabled for all origins!')
)

app.listen(80, function () 
  console.log('CORS-enabled web server listening on port 80')
)

或者,如果您想添加单个路由配置:

var express = require('express')
var cors = require('cors')
var app = express()

app.get('/products/:id', cors(), function (req, res, next) 
  res.json(msg: 'This is CORS-enabled for a Single Route')
)

app.listen(80, function () 
  console.log('CORS-enabled web server listening on port 80')
)

更具体的配置可以查看官方文档,非常简单直接

【讨论】:

感谢您的贡献。但是问题指定了“TypeScript”,因此这个答案无效。

以上是关于如何在 typescript express 中设置 cors()的主要内容,如果未能解决你的问题,请参考以下文章