首页 > 解决方案 > Express 和 Typescript : res: 响应未定义

问题描述

嗨,我正在使用 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;

路线.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;

应用程序.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;

用户控制器正在被主路由器使用的用户路由内部初始化。

标签: node.jstypescriptexpress

解决方案


问题是您正在调用控制器方法而不是将它们传递给路由器,从而导致它们在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);

推荐阅读