Express和Typescript:res:响应未定义

时间:2018-06-08 10:37:44

标签: node.js typescript express

您好我正在使用typescript来构建节点/表达restful api。

但是我收到以下错误:这对应于res.json('hello')

中的行users/user.controller.ts
  

TypeError:无法读取未定义的属性'json'

用户/ user.controller.ts

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

    class UserController {

        constructor() {

        }

        public index(req: Request, res: Response): void {

            res.json('hello');

        }

        public show(req: Request, res: Response): void {

        }

        public store(req: Request, res: Response): void {

        }

        public update(req: Request, res: Response): void {

        }

        public destroy(req: Request, res: Response): void {

        }
    }

    export default UserController;

用户/ user.route.ts

import { Router } from 'express';

import UserController from './user.controller';

class UserRouter {

    router: Router;
    controller: any;

    constructor() {

        this.router = Router();
        this.controller = new UserController;

        this.router.get('/', this.controller.index());
        this.router.get('/:id', this.controller.show());
        this.router.post('/', this.controller.store());
        this.router.put('/:id', this.controller.update());
        this.router.delete('/:id', this.controller.destroy());

    }
}

export default new UserRouter().router;

routes.ts

import { Router } from 'express';
import UserRouter from './app/users/user.router';

class Routes {

    public router: Router;

    constructor() {

        this.router = Router();

        this.router.use('/', (req, res, next) => {
            res.json('App / Server Running');
        })

        this.router.use('/users', UserRouter);

}

export default new Routes().router;

app.ts

import dotenv from 'dotenv';
import express from 'express';
import logger from 'morgan';
import bodyParser from 'body-parser';
import mongoose from 'mongoose';
import passport from 'passport';
import cors from "cors";

import Routes from './routes';
import Config from './config/app';


class App {

    public app: express.Application;
    public config: any;

    constructor() {

        this.app = express();

        this.environment();
        this.database();
        this.middleware();
        this.routes();

    }

    private environment(): void {

        dotenv.load({ path: '.env' });
        this.config = new Config();

    }

    private database(): void {

        const uri: string = this.config.db.uri;
        const options: any = this.config.db.options;

        mongoose.connect(uri, options).then(

            () => {
                console.log("MongoDB Successfully Connected On: " + this.config.db.uri)
            },
            (err: any) => {
                console.error("MongoDB Error:", err);
                console.log('%s MongoDB connection error. Please make sure MongoDB is running.');
                process.exit();
            }

        );

    }

    private middleware(): void {

        this.app.use(cors());
        this.app.use(logger('dev'));
        this.app.use(bodyParser.json());
        this.app.use(bodyParser.urlencoded({ extended: false }));

    }

    private routes(): void {

        this.app.use('/', Routes);

    }

}

export default App;

用户控制器正在主路由器使用的用户路由中进行初始化。

1 个答案:

答案 0 :(得分:1)

问题在于您调用控制器方法而不是将它们传递给路由器,导致它们在构造UserRouter后立即执行未定义的参数 - 请参阅以下行:

this.router.get('/', this.controller.index());
this.router.get('/:id', this.controller.show());
this.router.post('/', this.controller.store());
this.router.put('/:id', this.controller.update());
this.router.delete('/:id', this.controller.destroy());

它应该看起来像这样:

this.router.get('/', this.controller.index);
this.router.get('/:id', this.controller.show);
this.router.post('/', this.controller.store);
this.router.put('/:id', this.controller.update);
this.router.delete('/:id', this.controller.destroy);