admin管理员组文章数量:1332889
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.
4 Answers
Reset to default 3The 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();
};
本文标签: javascriptProperty 39authorization39 does not exist on type 39Request39Stack Overflow
版权声明:本文标题:javascript - Property 'authorization' does not exist on type 'Request' - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742304137a2449574.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论