要求与Express路由器导入到前缀路由

时间:2017-07-22 21:45:11

标签: node.js express typescript

我刚刚开始使用Node,并尝试使用带有Node的TypeScript,使用我在Angular中学到的Typescript。遵循MDN's Express Route示例(大约一半),因此我可以使用/auth为一组路由添加前缀。他们使用require('./routes/auth');获取导出的路由器,据我所知,使用import * as authRoutes from './routes/auth';基于docs和stackoverflow答案是等效的。这显然不是真的,因为我无法做到这一点:

import * as authRoutes from './routes/auth';
app.use('/auth', authRoutes); // Does not work?

VSCode突出显示'/auth'参数并显示此错误[ts] Argument of type '"/auth"' is not assignable to parameter of type 'RequestHandlerParams'

虽然这确实有效:

const authRoutes = require('./routes/auth');
app.use('/auth', authRoutes); // Does work!

来自MDN的路由示例:

import * as express from 'express';
import { Router, Request, Response, NextFunction } from 'express';

import * as authController from '../controllers/auth.controller';

const router: Router = express.Router();

router.get('/register', (req: Request, res: Response, next: NextFunction) => {
  authController.register(req, res);
});

router.get('/login', (req: Request, res: Response, next: NextFunction) => {
  authController.login(req, res);
});

module.exports = router;

有人可以在非常高层次上解释我所缺少的东西吗?我在博客中找到了什么可能是答案,但显然没有以有助于我理解的方式解释它们。

更新

似乎这是一个组合的东西,因为如果我export { router as authRoutes }然后它起作用,但我不知道我是否应该这样做,或者输出和导入的正确方法是什么我们的代码应该跟随其他文件。

1 个答案:

答案 0 :(得分:0)

在您的路线定义中,导出路由器: SELECT customer_id, COUNT(*) as number_of_orders, SUM(amount) AS total_amount FROM cust_orders WHERE year(order_date) = 2017 -- filters records before grouping. GROUP BY customer_id -- groups while counting and summing up. HAVING COUNT(*) > 2 -- count is available here.

在您的应用中导入它: export { router };