【发布时间】:2020-08-12 08:26:53
【问题描述】:
我已经创建了 registerClass,我将在其中添加此应用程序的所有路由,此节点应用程序正在使用 typescript,因此所有源代码都在 dist 目录中。当我调用 http://localhost:9001/user 端点时,我在下面的代码中缺少什么,它不会进入 registerRouteClass ?我猜它没有读取 dist 目录
server.js
const express = require("express"),
path = require("path"),
app = express();
var router = require('./dist');
app.use(express.static(path.join(__dirname, 'dist')));
app.use(new router.TRouter().getRouter);
app.listen(9001, () => console.log('Example app listening on port 9001!'));
routes.ts
import {UserController} from './api/user/user.controller';
export class RegisterRouteClass {
public RegisterRoutes(app: any) {
console.log("registing routes");
app.post('/user', UserController.findAll);
}
}
index.ts
import {NextFunction, Request, Response, Router} from 'express';
import * as bodyParser from 'body-parser';
import {RegisterRouteClass} from "./routes";
// this variable will be exported to be included as a middleware.
class TRouter extends RegisterRouteClass {
private TRouter: any;
constructor() {
super();
this.TRouter = Router();
this.TRouter.use(bodyParser.json());
this.TRouter.use(bodyParser.urlencoded({extended: false}));
this.TRouter.use(function(_req: Request, res: Response, next: NextFunction) {
// CORS header
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
res.setHeader("Content-Type", "application/json");
next();
});
}
public get getRouter() {
return this.TRouter;
}
}
export {TRouter};
目录结构
Project
- dist
-index.js
-routes.js
-api
- user
-user.constrollr.js
-server.js
【问题讨论】:
标签: javascript node.js typescript express express-router