“请求”类型上不存在属性“授权”

问题描述 投票:0回答:3

考虑这段代码:

  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 错误:

“请求”类型上不存在属性“授权”。

这来自于尝试访问

completeHeader.headers.authorization
。属性
authorization
确实在
Express.request
接口上不可用。奇怪的是,TypeScript 无法从文字对象推断出类型,而文字对象显然属于
string
类型。当未定义类型时
as Express.Request
会抛出有关不安全的任何赋值的错误。

是否需要专门为这一字段创建一个新的TS接口?或者我们使用了不正确的类型?字段

authorization
看起来像是发送令牌的常用字段。

javascript typescript express
3个回答
3
投票

原因是因为你将
completeHeader.headers
强制转换为
Express.Request
类型。 强制类型会覆盖推断类型。

您可以做的是通过执行以下操作来扩展强制类型:

as Express.Request & { authorization: string }

或者你可以创建一个全新的类型:

type AuthorizedRequest = Express.Request & { authorization: string };
...
as AuthorizedRequest 

1
投票

就我而言,我需要添加用户,并且授权头中出现错误(req.headers.authorization),我的解决方法是:

案例一: 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。在名为“types”的文件夹中,我创建了文件 并补充道:

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);
        }
    };

我希望也许会对某人有所帮助


0
投票
import * as jwt from "jsonwebtoken";
import { NextFunction, Request } from "express";
try{
const authorizationHeader = req.headers.authorization;
//logic for decryption of token and validating empty authorisation header
}

只需要从express导入Request,它会自动推断req标头中存在授权

© www.soinside.com 2019 - 2024. All rights reserved.