本文介绍了打字稿错误:类型“请求"上不存在属性“用户"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的快速应用中有以下代码

I have the following piece of code in my express app

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

并且我的IDE似乎在抱怨该错误

and my IDE seems to be complaining with the error

编译我的打字稿代码时,似乎抛出了此错误.任何想法为什么会这样?

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

推荐答案

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

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

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

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

请注意,用户"不是Express的Request对象中本机可用的属性.确保您正在使用将此类属性添加到请求对象的中间件.

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.

这篇关于打字稿错误:类型“请求"上不存在属性“用户"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 05:51