[英]how to set up cors() in typescript express
在我的一個項目中,這很有效:
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)
然后我嘗試設置自定義 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());
這次我遇到了另一個可愛的錯誤:
沒有過載匹配此調用。 最后一個重載給出了以下錯誤。 'Response | 類型的參數 undefined' 不可分配給 'RequestHandlerParams<ParamsDictionary, any, any, ParsedQs>' 類型的參數。 類型“未定義”不可分配給類型“RequestHandlerParams<ParamsDictionary, any, any, ParsedQs>”
這是因為 cors 庫的通用類型存在一些歧義。 我發現解決此問題的最簡單方法就是明確指定cors
方法的請求類型。
import { Request } from "express";
import cors from "cors";
server.use(cors<Request>());
來自快遞官方文檔:
對於所有 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')
})
對於更具體的配置,您可以查看官方文檔,它們非常簡單明了
就我而言:
{
"cors": "^2.8.5",
"express": "^4.18.1",
"typescript": "^4.8.4",
}
有用:
import cors = require("cors");
app.use(cors<Request>());
我找到了這個解決方案:
使用:
...
"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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.