简体   繁体   English

Typescript&Express:将多个路由从单个index.ts文件导出到前缀为“ / api / v1”的文件

[英]Typescript & Express: Export several routes from single index.ts file to prefix with ''/api/v1"

I am trying to tidy up my routes. 我正在努力整理路线。 I would like to have 1 file,index.ts, to export all my routes from. 我想要1个文件index.ts来导出所有路由。 I have seen something similar done in plain JavaScript but not sure on the syntax in typescript. 我已经在普通JavaScript中看到了类似的内容,但不确定打字稿中的语法。

The error I get is: TypeError: Router.use() requires a middleware function but got a Object

(old but works)BaseRoutes.ts (旧但有效)BaseRoutes.ts

import * as express from 'express';
import {PostRoutes} from '../PostRoutes';
import {CspRoutes} from '../CspRoutes';
import {CustomerPreferenceRoutes} from '../CustomerPreferenceRoutes';
import { SalesOrderRoutes } from '../SalesOrderRoutes';
let app = express();
const BASE_API: string = '/api/v2';
class BaseRoutes{
    get routes(){
        app.use(BASE_API, new PostRoutes().routes);
        app.use(BASE_API, new CspRoutes().routes);
        app.use(BASE_API, new CustomerPreferenceRoutes().routes);
        app.use(BASE_API, new SalesOrderRoutes().routes);
        return app;
    }
}
export {BaseRoutes}

(new does not work)BaseRoutes.ts (新功能不起作用)BaseRoutes.ts

import * as express from 'express';

let routes = require('../index');
let app = express();
const BASE_API: string = '/api/v2';

class BaseRoutes{
    get routes(){
        app.use(BASE_API,routes);
        return app;
    }
}
export {BaseRoutes}

PostRoutes.ts PostRoutes.ts

import * as express from 'express';
import {PostController} from '../../controllers/PostController'

let router = express.Router();

class PostRoutes{
    private _postController:PostController;
    constructor(){
        this._postController = new PostController();
    }
    get routes(){
        let controller = this._postController
        router.get('/posts',controller.retrieve)
        router.get('/posts/:_id',controller.findById)
        return router;
    }
}
export{PostRoutes};

index.ts 索引

export * from './PostRoutes';
export * from './SalesOrderRoutes';

It is because you messed up your imports. 这是因为您搞砸了进口商品。

export * from './PostRoutes';
export * from './SalesOrderRoutes';

You are re-exporting all the exports from PostRoutes and SalesOrderRoutes etc. , so when you finally import it in BaseRoutes , you actually import all the constructors you exported in each route. 您将重新导出PostRoutesSalesOrderRoutes等的所有导出,因此,当最终将其导入BaseRoutes ,实际上就是导入在每个路由中导出的所有构造函数。

What you want to do is: 您想要做的是:

import { PostRoutes, SalesOrderRoutes } from '../index';

And then use() each route explicitly. 然后显式地使用()每个路由。

Edit: You can read more about Typescript modules and Javascript modules 编辑:您可以阅读有关Typescript模块Javascript模块的更多信息


声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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