考虑以下代码:
setContext(async (req, { headers }) => {
const token = await getToken(config.resources.gatewayApi.scopes)
const completeHeader = {
headers: {
...headers,
authorization:
token && token.accessToken ? `Bearer ${token.accessToken}` : '',
} as Express.Request,
}
console.log('accessToken: ', completeHeader.headers.authorization)
return completeHeader
})
生成以下TS错误:
类型"Request"上不存在属性"authorization"。
这来自于尝试访问completeHeader.headers.authorization
。属性authorization
在Express.request
接口上确实不可用。奇怪的是,TypeScript不能从字面对象推断类型,而字面对象显然是string
类型。当没有定义类型as Express.Request
时,会引发关于不安全的任意赋值的错误。
是否需要为这一字段创建一个新的TS接口?还是我们使用了不正确的类型?字段authorization
看起来像是用于发送令牌的常用字段。
原因是您将completeHeader.headers
强制转换为Express.Request
类型强制类型覆盖推断类型
你可以做的是,通过以下操作来扩展强制类型:
as Express.Request & { authorization: string }
或者你可以创建一个全新的类型:
type AuthorizedRequest = Express.Request & { authorization: string };
...
as AuthorizedRequest
在我的情况下,我需要添加user&我在带有授权的标头中出错(req.headers.authorization(,我的解决方案是:
案例1:1.1.哪里有错误(req.headers.authorization(,但在我收到类似的错误之前,用户:
import { IAuthRequest } from "./../types/user.type";
const checkAuth =
() => async (req: IAuthRequest, res: Response, next: NextFunction) => {
try {
//2. Second i got error here(main problem)
//i got if, i set <req:IRequestUser> for resolve
//problem with <req.user>: Property 'authorization'
//does not exist on type 'Headers'.
//And you need to change <req: IAuthRequest>, and
//resolve problems
if (!req.headers.authorization) throw new Error("Please log in");
const token = req.headers.authorization.split(" ")[1];
if (!process.env.SECRET_ACCESS_TOKEN)
throw new Error("Please create <SECRET_ACCESS_TOKEN> in .env file");
const { decoded, expired } = Jwt.verifyJwtToken(
token,
process.env.SECRET_ACCESS_TOKEN
);
if (expired) return res.status(401).send("Token has been expired");
//1. first error here
//before(Property 'authorization' does not exist on
//type 'Headers'.) i have got error here(Property
//'user' does not exist on type 'Request'.), if
//<req: Request>, you can try resolve this problem
//<req: IRequestUser> and after this, i got error
//with req.headers.authorization (see <2. Second i
//got error ...>, code above)
req.user = decoded;
next();
} catch (err) {
return res.status(400).send(err);
}
};
1.2、在名为"like"的文件夹中;类型";,我已经创建了文件<user.type.ts>并添加:
export interface IUserData {
_id: string;
email: string;
username: string;
}
export interface IRequestUser extends Request {
user: IUserData;
}
export type IAuthRequest = IRequestUser & {
headers: { authorization: string };
};
你只需要删除注释,上面的代码就会正常工作,注释只是为了理解错误之前代码中的内容,以及我如何解决这个问题
案例2:过了一段时间,我发现了一种更简单的方法:
import { IAuthRequest } from "./../types/user.type";
const checkAuth =
() => async (req: Request, res: Response, next: NextFunction) => {
try {
req as IAuthRequest;
//your code...
next();
} catch (err) {
return res.status(400).send(err);
}
};
我希望它能帮助