我想使用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 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);
错误在app.use(cors({ origin: true });
答案 0 :(得分:1)
Specifying the path is optional for use
和cors docs完全显示了您作为有效示例所做的工作。 IOW,您的代码很棒!那里没问题。
最近,快速类型定义发生了变化。似乎有两组:@types/express和@types/express-serve-static-core。前者取决于后者,并且express-serve-static-core
中的there seems to be some breaking changes尚未@types/express
赶上。
在该线程中,提出了一些解决方法。
您可以将@types/express
中package.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);