javascript - Property 'authorization' does not exist on type 'Request' - Stack Overflow

Consider this code:setContext(async (req, { headers }) => {const token = await getToken(config.resou

Consider this code:

  setContext(async (req, { headers }) => {
    const token = await getToken(config.resources.gatewayApi.scopes)

    const pleteHeader = {
      headers: {
        ...headers,
        authorization:
          token && token.accessToken ? `Bearer ${token.accessToken}` : '',
      } as Express.Request,
    }

    console.log('accessToken: ', pleteHeader.headers.authorization)
    return pleteHeader
  })

Which generates the following TS error:

Property 'authorization' does not exist on type 'Request'.

This es from trying to access pleteHeader.headers.authorization. The property authorization is indeed not available on the Express.request interface. It's strange that TypeScript can't infere the type from the literal object, which clearly is of type string. When not defining the type as Express.Request an error is thrown about an unsafe any assignment.

Is it required to create a new TS interface just for this one field? Or are we using an incorrect type? The field authorization looks to be like a monly used field for sending tokens.

Consider this code:

  setContext(async (req, { headers }) => {
    const token = await getToken(config.resources.gatewayApi.scopes)

    const pleteHeader = {
      headers: {
        ...headers,
        authorization:
          token && token.accessToken ? `Bearer ${token.accessToken}` : '',
      } as Express.Request,
    }

    console.log('accessToken: ', pleteHeader.headers.authorization)
    return pleteHeader
  })

Which generates the following TS error:

Property 'authorization' does not exist on type 'Request'.

This es from trying to access pleteHeader.headers.authorization. The property authorization is indeed not available on the Express.request interface. It's strange that TypeScript can't infere the type from the literal object, which clearly is of type string. When not defining the type as Express.Request an error is thrown about an unsafe any assignment.

Is it required to create a new TS interface just for this one field? Or are we using an incorrect type? The field authorization looks to be like a monly used field for sending tokens.

Share Improve this question asked Aug 20, 2020 at 11:45 DarkLite1DarkLite1 14.8k46 gold badges136 silver badges234 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 3

The reason is because you're coercing pleteHeader.headers into the Express.Request type. The coerced type overrides the inferred type.

What you can do, is expand that coerced type by doing the following:

as Express.Request & { authorization: string }

or you could create an entirely new type:

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

in my case, I needed to add user & I got error in headers with authorization(req.headers.authorization), me resolve was:

Case 1: 1.1. Where was error(req.headers.authorization), but before i had got similar error but with user:

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. In folder named like "types", i have created file <user.type.ts> and added:

export interface IUserData {
    _id: string;
    email: string;
    username: string;
}

export interface IRequestUser extends Request {
    user: IUserData;
}

export type IAuthRequest = IRequestUser & {
    headers: { authorization: string };
};

You need just delete ments and code above will work correctly, ment only for understanding what was in code before error, and how i resolve this problems

Case 2: after a while I found an even easier way:

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

i hope that maybe it will help to someone

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
}

just need to import Request from express it will automatically infer that authorization exists on req headers

Be make sure you import the Request, Response and NextFunction from express.

     import { NextFunction, Request, Response } from "express"; 
    
     export default (req: Request, res: Response, next: NextFunction) => {
       const token = req.headers.authorization;
     next(); 
};

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742304139a4418597.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信