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

时间:2019-12-04 00:17:09

标签: reactjs firebase express cors 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.

我使用yarn add cors expressyarn 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);

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

3 个答案:

答案 0 :(得分:1)

Specifying the path is optional for usecors docs完全显示了您作为有效示例所做的工作。 IOW,您的代码很棒!那里没问题。

最近,快速类型定义发生了变化。似乎有两组:@types/express@types/express-serve-static-core。前者取决于后者,并且express-serve-static-core中的there seems to be some breaking changes尚未@types/express赶上。

在该线程中,提出了一些解决方法。

您可以将@types/expresspackage.json的版本固定为4.17.0的版本。或者,您可以使用Typescript compiler's skipLibCheck标志来禁用库检查。

答案 1 :(得分:0)

我相信您的说法是错误的。根据{{​​3}}这里的官方文档,您像api.use(cors())那样“使用”

当您像这样的“调用” cors时,您会传递选项

api.get('/products/:id', cors(corsOptions), function (req, res, next) { 
res.json({msg: 'This is CORS-enabled for only example.com.'}) 
})

所以您的情况将类似于

api.get('/products/:id', cors({ origin: true}), function (req, res, next) { 
    res.json({msg: 'This is CORS-enabled for only example.com.'}) 
    })

答案 2 :(得分:0)

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

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