简体   繁体   中英

TypeScript : TypeError: Cannot set property 'test' of undefined

I'm trying to learn TypeScript but there's some notion that I don't understand correctly...

I have this Error:

TypeError: Cannot set property 'test' of undefined
    at testResponse (/home/mcfly/bimbim/geoloc_API/dist/routes/geoRouter.js:11:19)

and I don't know how to fix it.

import {
  Router, Request, Response,
} from 'express';

export class GeoRouter {
  router : Router

  test : string

  constructor() {
    this.router = Router(); // the error point here... Why ?
//              ^-------------------|
    this.init();
  }

  public testResponse(_req: Request, _res: Response) {
    this.test = _req.params.addr;
    _res.send(this.test);
  }

  init() {
    this.router.get('/:addr', this.testResponse);
  }
}

const geoRoutes = new GeoRouter();
geoRoutes.init();

export default geoRoutes.router;

Someone got an idea?

You need to specify the the req parameter on the: this.router.get(url, req, res);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM