node.js 打字稿错误:“请求”类型上不存在“用户”属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44383387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:16:25  来源:igfitidea点击:

Typescript Error: Property 'user' does not exist on type 'Request'

node.jstypescript

提问by RRP

I have the following piece of code in my express app

我的快递应用程序中有以下一段代码

router.get('/auth/userInfo', this.validateUser,  (req, res) => {
    res.json(req.user);
});

and my IDE seems to be complaining with the error

我的 IDE 似乎在抱怨错误

error TS2339: Property 'user' does not exist on type 'Request'.

错误 TS2339:“请求”类型上不存在属性“用户”。

When I compile my typescript code it seems to be throwing this error. Any ideas why this is happening?

当我编译我的打字稿代码时,它似乎抛出了这个错误。任何想法为什么会发生这种情况?

回答by Akshar Patel

We have a large API written in Express and Typescript, and this is how we handle such scenarios:

我们有一个用 Express 和 Typescript 编写的大型 API,这就是我们处理此类场景的方式:

We keep the request definitions in one file:

我们将请求定义保存在一个文件中:

import { Request } from "express"
export interface IGetUserAuthInfoRequest extends Request {
  user: string // or any other type
}

And then in the file where we are writing the controller functions:

然后在我们编写控制器函数的文件中:

import { Response } from "express"
import { IGetUserAuthInfoRequest } from "./definitionfile"

app.get('/auth/userInfo', validateUser,  (req: IGetUserAuthInfoRequest, res: Response) => {
  res.status(200).json(req.user); // Start calling status function to be compliant with Express 5.0
});

Be advised that "user" is not a property that is available natively in the Request object of Express. Make sure that you are using a middleware that adds such property to the request object.

请注意,“用户”不是 Express 的请求对象中本机可用的属性。确保您使用的是将此类属性添加到请求对象的中间件。

回答by Lostfields

req is probably of type Request from "express" package and user does not exist there. You have to either extend Request with own router handler or cast it to type any or object.

req 可能是来自“express”包的请求类型,用户在那里不存在。您必须使用自己的路由器处理程序扩展 Request 或将其转换为类型 any 或 object。

try res.json(req['user'])or res.json( (<any>req).user )

尝试res.json(req['user'])res.json( (<any>req).user )

You may also use module/global augmentation

您也可以使用模块/全局增强

import { Request } from "express"

declare module "express" { 
  export interface Request {
    user: any
  }
}

You can also make your own handler wrapper (instead of extending Router functionality in ExpressJs).

您还可以制作自己的处理程序包装器(而不是在 ExpressJs 中扩展路由器功能)。

import * as express from 'express';

interface IUserRequest extends express.Request {
    user: any
}

function myHandler(handler: (req: IUserRequest, res: express.Response, next?: express.NextFunction) => any) {
    return (req: express.Request, res: express.Response, next: express.NextFunction) => {
        try {

            validateUser(req, res, (err) => { // your validateUser handler that makes a user property in express Request
                if(err)
                     throw err;

                let requestWrapper: IUserRequest = <IUserRequest>req;

                handler(requestWrapper, res, next);
            })                
        }
        catch (ex) {
            next(ex);
        }
    } 
}

let app = express();
// init stuff for express but this.validateUser handler is not needed

app.use('/testuser', myHandler((req, res) => {
    res.json(req.user);
}));

回答by duliba

You're getting this error because there's no type definition for the userproperty in the the native express Requestobject. You should install the type definitions for the middleware you're using to add userto the request.

您收到此错误是因为user本机express Request对象中没有属性的类型定义。您应该安装用于添加user到请求中的中间件的类型定义。

For example, if you're using the passportlibrary for JWT authentication as middleware:

例如,如果您使用passportJWT 身份验证库作为中间件:

router.get('/auth/userInfo', passport.authenticate('jwt', {session:false}), (req, res, next) => {
  // Get their info from the DB and return it
  User.findOne({ email: req.user.email }, (err, user) => {
    if (err) {return next(err);}
    ...
    ...

You should add the type definitions for passport:

您应该添加以下类型的定义passport

npm install --save @types/passport

回答by SpBills

For people using GraphQL, there comes a problem with the graphqlExpressfunction not accepting your new interface. I was attempting to follow this guideuntil I ran into this exact problem. I have figured out this solution:

对于使用 GraphQL 的人来说,graphqlExpress函数不接受新的interface. 我一直在尝试遵循本指南,直到遇到这个确切的问题。我想出了这个解决方案:

this.app.use("/graphql", bodyParser.json(), this.auth, graphqlExpress((req: AuthRequest | undefined) => ({ 
    schema,
    context: {
        user: req!.user
    }
})));

And in the AuthRequestinterface:

并在AuthRequest界面中:

import {Request} from "express"

export interface AuthRequest extends Request {
    user?: string
}

Typescript will not allow you to use AuthRequest unless it is also allowed to be undefined. Therefore the | undefined. (source)

Typescript 不允许您使用 AuthRequest,除非它也被允许未定义。因此| undefined. (来源

After this point, the user object does not 100% exist on the Request object, hence the ? after user.

在这一点之后,用户对象不是 100% 存在于请求对象上,因此?用户后。

回答by Caphson

Old question but if anyone stumbles across this like I did, take a look at 'Declaration Merging' - solved the issue for me.

老问题,但如果有人像我一样偶然发现了这个问题,请查看“声明合并” - 为我解决了这个问题。

https://www.typescriptlang.org/docs/handbook/declaration-merging.html

https://www.typescriptlang.org/docs/handbook/declaration-merging.html

https://truetocode.com/extend-express-request-and-response-typescript-declaration-merging/

https://truetocode.com/extend-express-request-and-response-typescript-declaration-merging/

回答by Amila Weerasinghe

I was using okta-angular-node with express for this https://developer.okta.com/blog/2018/10/30/basic-crud-angular-and-node

我正在使用 okta-angular-node 和 express 这个https://developer.okta.com/blog/2018/10/30/basic-crud-angular-and-node

I came up with similar error for req.user. Please check the server/auth.ts inside the above given link.

我想出了类似的错误req.user。请检查上面给出的链接中的 server/auth.ts。

Type casting worked for me. Try to cast as follows

类型转换对我有用。尝试按如下方式投射

req.userto (req['user'])

req.user(req['user'])