Node js Typescript基本控制器具有路由器,它绑定到相同的路由

时间:2019-06-09 15:29:19

标签: node.js typescript

我有两个api端点。 / api / comment / vote和/ api / highlight / vote。 当我调用/ api / comment / vote时,它可以工作,但是当我调用/ api / hifhlight / vote时,它不起作用,它仍然调用/ comment / vote。

export class BaseController {
    private _router: express.Router;
    constructor() {
        this._router = router;
    }

    public get router(){
        return this._router;
    }

    protected getToken(user: IUser) {
        let payload = {
            subject: user._id
        }
        return jwt.sign(payload, 'secretKey');
    }
}

CommentController从BaseController扩展


class CommentController extends BaseController {
    constructor() {
        super();
        this.bindToRouter();
    }

    bindToRouter() {
        this.router.post('/vote',authorizationHelper.authorized, this.postVote.bind(this));
    }


    async postVote(req: express.Request, res: express.Response) {
        //some code
    }
}

HighlightController是从BaseController扩展的(与上面的相同)

export class HighlightController extends BaseController {
    constructor() {
        super();
        this.bindToRouter();
    }

    bindToRouter() {

        this.router.post('/vote',authorizationHelper.authorized, this.postVote.bind(this));
    }

    async postVote(req: express.Request, res: express.Response) {
        //some code
    }
}



import express = require('express');
import { HighlightController } from './highlight';
const router = express.Router();


const mongoose = require('mongoose');
const db = "***HAHAHAHA***";

const authentification = require('./authentification');
const user = require('./user');
const translator = require('./translator');
const post = require('./post');
const team = require('./team');
const comment = require('./comment');
//const highlight = require('./highlight');

mongoose.connect(db, { useNewUrlParser: true, useFindAndModify: false }, (err: Error) => {
    if (err) {
        console.log(err);
    }
    else {
        console.log("Connected to mongodb");
    }
});

router.get('/', (req: any, res: any) => {
    res.send('From API route');
});

router.use('/authentification', authentification);
router.use('/user', user);
router.use('/translator', translator);
router.use('/post', post);
router.use('/team', team);
router.use('/highlight', new HighlightController().router);
router.use('/comment', comment);

我尝试了多种导出和导入方式。

当我更改路线时它可以工作,例如,一个是/ comment / votea,另一个是/ comment / voteb。

0 个答案:

没有答案