【问题标题】:Property 'authorization' does not exist on type 'Request'“请求”类型上不存在属性“授权”
【发布时间】:2020-08-20 11:45:17
【问题描述】:

考虑这段代码:

  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.authorizationauthorization 属性在Express.request 接口上确实不可用。奇怪的是,TypeScript 无法从字面量对象中推断出类型,而字面量对象显然是string 类型。如果未定义类型 as Express.Request,则会引发有关不安全的 any 分配的错误。

是否需要为这一领域创建一个新的TS接口?还是我们使用了不正确的类型? authorization 字段看起来像是发送令牌的常用字段。

【问题讨论】:

    标签: javascript typescript express


    【解决方案1】:

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

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

    as Express.Request & { authorization: string }
    

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

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

    【讨论】:

    • 我也试过(token && token.accessToken ? Bearer ${token.accessToken}` : '') as string`,但没有奏效。你的建议很完美,谢谢。
    【解决方案2】:

    在我的情况下,我需要添加用户并且我在授权的标题中遇到错误(req.headers.authorization),我的解决方案是:

    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. 在名为 like 的文件夹中,我创建了文件 并补充说:
    export interface IUserData {
        _id: string;
        email: string;
        username: string;
    }
    
    export interface IRequestUser extends Request {
        user: IUserData;
    }
    
    export type IAuthRequest = IRequestUser & {
        headers: { authorization: string };
    };
    

    您只需要删除 cmets,上面的代码就可以正常工作,注释仅用于了解错误前代码中的内容以及我如何解决此问题

    我希望它可能对某人有所帮助

    【讨论】:

      猜你喜欢
      • 2022-07-13
      • 2020-03-16
      • 1970-01-01
      • 2017-11-03
      • 2020-05-20
      • 2021-01-21
      • 1970-01-01
      • 2016-05-17
      • 2019-05-15
      相关资源
      最近更新 更多