【问题标题】:Why do I have this error «Cannot read property 'authService' of undefined»为什么我有这个错误 «Cannot read property 'authService' of undefined»
【发布时间】:2020-07-18 19:55:55
【问题描述】:

请求POST/auth/signup时,弹出错误 Gist code

TypeError:无法读取未定义的属性“authService” 在 F:_node-projects\price-monitoring-backend\build\controllers\auth.controller.js:54:41 在步骤 (F:_node-projects\price-monitoring-backend\build\controllers\auth.controller.js:33:23) 在 Object.next (F:_node-projects\price-monitoring-backend\build\controllers\auth.controller.js:14:53) 在 F:_node-projects\price-monitoring-backend\build\controllers\auth.controller.js:8:71 在新的承诺 () 在 __awaiter (F:_node-projects\price-monitoring-backend\build\controllers\auth.controller.js:4:12) 在 AuthController.signUp (F:_node-projects\price-monitoring-backend\build\controllers\auth.controller.js:45:16) 在 Layer.handle [as handle_request] (F:_node-projects\price-monitoring-backend\node_modules\express\lib\router\layer.js:95:5) 在下一个(F:_node-projects\price-monitoring-backend\node_modules\express\lib\router\route.js:137:13) 在 Route.dispatch (F:_node-projects\price-monitoring-backend\node_modules\express\lib\router\route.js:112:3) 在 Layer.handle [as handle_request] (F:_node-projects\price-monitoring-backend\node_modules\express\lib\router\layer.js:95:5) 在 F:_node-projects\price-monitoring-backend\node_modules\express\lib\router\index.js:281:22 end\node_modules\express\lib\router\index.js:317:13) 在 F:_node-projects\price-monitoring-backend\node_modules\express\lib\router\index.js:284:7 在 Function.process_params (F:_node-projects\price-monitoring-backend\node_modules\express\lib\router\index.js:335:12) 在下一个(F:_node-projects\price-monitoring-backend\node_modules\express\lib\router\index.js:275:10) 在 hpp (F:_node-projects\price-monitoring-backend\node_modules\hpp\lib\index.js:146:9)

【问题讨论】:

  • 你能分享完整的错误,包括行号等吗?
  • @Evert 添加了它

标签: typescript express


【解决方案1】:

这是由这一行引起的:

const result = await this.authService.signup(userData)

它在一个属于类的函数中。但是,当您将此函数传递给您的路由时,您会丢失对this 的引用:

this.router.post(`${this.path}/signup`, this.authController.signUp)

要保留this 范围,您需要将其绑定到自身:

this.router.post(`${this.path}/signup`, this.authController.signUp.bind(this.authController))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    • 2019-01-11
    • 2019-08-13
    • 2023-02-10
    • 2020-05-10
    • 2020-03-03
    • 1970-01-01
    相关资源
    最近更新 更多