让 javascript ES 模块在 NodeJS 应用程序中工作

问题描述 投票:0回答:1

我有一个使用 NodeJS 和 ExpressJS 构建的 app.js 文件,它调用routes.js 文件进行 URL 处理,然后引用一个呈现我的模板/视图的controller.js 文件。我有多个使用 CommonJS 的路线,但是当我尝试将其全部转换为 ES 模块时,我遇到了问题。

以下代码适用于具有单个路由的路由文件。但是,我无法让它与多个路线一起使用。它需要一个

export default
来表示单个路由,这确实有效,或者如果我在单个 Route.js 文件中尝试多个路由,则会出现此错误:
Route.get() requires a callback function but got a [object Undefined]
。也许我的语法有问题,也许是别的原因。

这是我的工作代码,但是当我尝试添加多个路线时它会中断......

这是我对路由文件的 app.js 调用:

import shopRoutes from './routes/shop.js';
app.use(shopRoutes);

我从路由文件中调用控制器文件,如下所示:

import express from 'express';
import * as shopController from '../controllers/shop.js';
const router = express.Router();
const shopIndex = router.get('/', shopController.getIndex);
// need to be able to use more routes like this, etc
// const shopIndex = router.get('/product', shopController.getProducts);
export default shopIndex;

这是相关的控制器文件:

export const getIndex = (req, res, next) => {
  res.render('shop/index', {
    pageTitle: 'Shop',
    path: '/',
  });
};
// need to be able to use more functions for template assignment
// export const getProducts = (req, res, next) => {
//  res.render('shop/product', {
//    pageTitle: 'Product',
//    path: '/product',
//  });
// };

export default getIndex;

如何使用 ES6 模块在路由文件中包含多个路由,从而调用多个控制器函数?感谢任何和所有的帮助。

javascript node.js express es6-modules commonjs
1个回答
0
投票

首先,从您的控制器文件中删除默认导出。您已经将

getIndex
导出为命名导出,将其复制为默认导出并没有真正的意义。

然后,将您想要的任何路由处理程序添加到您的shop路由器并导出它

// controllers/shop.js

export const getIndex = (req, res, next) => {
  // ...
};

export const getProducts = (req, res, next) => {
  // ...
};
// routes/shop.js

import express from 'express';
import * as shopController from '../controllers/shop.js';

const router = express.Router();
router.get('/', shopController.getIndex);
router.get('/product', shopController.getProducts);

export default router;
// app.js
import shopRouter from './routes/shop.js';

app.use(shopRouter);
© www.soinside.com 2019 - 2024. All rights reserved.