我目前正在开发一个完整的身份验证应用程序与MERN堆栈,所有在 typescript 。但我遇到了一些问题(类型错误)与我的userController文件。
这是我的路由文件:
import { validate } from "../middlewares/validateMiddleware";
import { createUserSchema } from "../schemas/user.schema";
import { UserController } from "../controllers/user.controller";
function routes(app: Express) {
app.get("/", (req: Request, res: Response) => {
res.json({ message: "Hello World" });
});
// Local User Authentication and Authorization
const user = new UserController()
app.post("/auth/local/signup", validate(createUserSchema), user.createNewUser)
}
export { routes };
用户控制器档桉
import { Request, Response } from "express";
import { UserService } from "../services/user.service";
import { createUserInput } from "../schemas/user.schema";
import { CREATED, FORBIDDEN } from "http-status";
import log from "../utils/logger";
import { JwtStrategy } from "../auth/jwt";
export class UserController {
private userService: UserService;
private jwtStrategy: JwtStrategy;
constructor() {
this.userService = new UserService();
this.jwtStrategy = new JwtStrategy();
}
public async createNewUser(
req: Request<{}, {}, createUserInput["body"]>,
res: Response
) {
try {
const user = await this.userService.createNewUser(req.body);
return res.status(CREATED).json(user);
} catch (error) {
log.error(error);
return res.status(FORBIDDEN).send(error);
}
}
public async authenticateUser() {}
}
用户服务文件:
import { User, UserInput } from "../models/user.models";
export class UserService {
private model: typeof User;
constructor() {
this.model = User;
}
public async createNewUser(dto: UserInput) {
try {
return await this.model.create(dto);
} catch (error: any) {
throw new Error(error);
}
}
}
但我总是得到错误:TypeError:无法读取未定义的属性(阅读“userService”)
有什么问题吗?
"type": "TypeError",
"message": "Cannot read properties of undefined (reading 'userService')",
"stack":
TypeError: Cannot read properties of undefined (reading 'userService')
at /Desktop/Practices/Ts/Mern-Auth/src/controllers/user.controller.ts:21:31
}
任何帮助将不胜感激,我是相对新的使用快递。
1条答案
按热度按时间ttvkxqim1#
您丢失了
this
上下文你有几个选择
箭头函数
结合
在构造函数中绑定