Tuesday 6 June 2017

RESTful service using express and typescript - this undefined for Response.send()

Appears that "this" is undefined inside of a express.Response.send() method. Is there a way to still send a member of my Router?

my-router.ts:

import { Router, Request, Response, NextFunction } from 'express';
import { MyTsObject } from "../my-ts-object";

export class MyRouter {
    router: Router;
    myTsObject: MyTsObject;

    constructor() {
        this.myTsObject = new MyTsObject();
        this.router = Router();
        this.init();
    }

    public getData(req: Request, res: Response, next: NextFunction){
        res.send(JSON.stringify(this.myTsObject)); // runtime error here:
        // TypeError: Cannot read property 'myTsObject' of undefined
    }

    init() {
        this.router.get('/', this.getData);
    }
}

app.ts:

import * as express from 'express';
import * as logger from 'morgan';
import * as bodyParser from 'body-parser';
import { MyRouter } from "./routes/my-router";

class App {
    public express: express.Application;

    constructor() {
        this.express = express();
        this.middleware();
        this.routes();
    }

    private middleware(): void {
        this.express.use(logger('dev'));
        this.express.use(bodyParser.json());
        this.express.use(bodyParser.urlencoded({ extended: false}));
    }

    private routes(): void {
        this.express.use('/', new MyRouter().router);
    }

}

export default new App().express;

index.ts:

import * as  http from 'http';
import * as debug from 'debug';

import App from './app';

debug('ts-express:server');

const port = normalizePort(process.env.PORT || 3000);
App.set('port', port);

const server = http.createServer(App);
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

....

See the my-router.ts file for the runtime error that is occurring when I hit the url in a browser. I'm assuming 'this' in that context is not referring to the MyRouter object. Is there still a way to get a reference to the myTsObject from inside the send() method? Is there a better way to do all this?



via ZackDeRose

No comments:

Post a Comment