Cors TypeScript 中没有重载匹配此调用

Wah*_*wan 7 cors express firebase reactjs google-cloud-functions

我想使用 Express TypeScript 创建 API,但是当我想使用 cors 时,它显示如下错误:

No overload matches this call.
The last overload gave the following error.
Argument of type 'RequestHandler<any>' is not assignable to parameter of type 'PathParams'.
Type 'RequestHandler<any>' is missing the following properties from type '(string | RegExp)[]': length, pop, push, concat, and 26 more.
Run Code Online (Sandbox Code Playgroud)

我使用yarn add cors express和安装了软件包yarn add @types/cors @types/express

这是我的代码:

const api = express();
const main = express();

api.use(cors({ origin: true }));

main.use(bodyParser.json());
main.use(bodyParser.urlencoded({ extended: false }));
main.use("/api/v1", api);

export const webApi = functions.https.onRequest(main);
Run Code Online (Sandbox Code Playgroud)

错误在 app.use(cors({ origin: true });

M F*_*nga 10

为 指定路径是可选的usecors 文档准确地显示了您作为有效示例所做的工作。IOW,你的代码很棒!那里没有问题。

最近对 express 类型定义进行了更改。似乎有两组: @types/express@types/express-serve-static-core。前者依赖于后者,而且似乎有一些重大的变动express-serve-static-core那个@types/express还没有完全赶上了呢。

在该线程中,提出了几种解决方法。

你可以将版本@types/express在你package.json到版本4.17.0。或者您可以使用Typescript 编译器的 skipLibCheck标志禁用库检查。


小智 6

对我有用的只是之前声明了一个变量:

const corstOpts = cors({ origin: true })
api.use(corstOpts);
Run Code Online (Sandbox Code Playgroud)