如何对快递路线进行分组,如快递组路线?

How to group express routes like express-group-routes?

我尝试使用 express-group-routes 并在我的本地主机上运行良好但在 docker 容器[=19] 上启动时未检测到任何路由=]

我有简单的代码 returns JSON 如下:

{
    "message": "Service Running"
}

和其他路线。

小型 Expressjs 服务在 Ubuntu 上与 node src/server.js 配合得很好,每条路线都找到了。

当我将代码容器化时,问题就来了。

DockerFile 看起来像这样

FROM node:12.18.2-alpine3.12

ENV PORT=3000

EXPOSE ${PORT}

COPY . /app

WORKDIR /app

RUN npm install

CMD ["node", "src/server.js"]

server.js 看起来像这样

const express = require("express");
const bodyParser = require("body-parser");
const app = express();

// parse requests of content-type: application/json
app.use(bodyParser.json());

// parse requests of content-type: application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));

var { router } = require('./routes/index');

const port = process.env.PORT || 3000;
app.use(router);

app.listen(port,() => console.log("Server started :::", new Date().getTime()));

路由文件如下所示

const util = require('../util/util');
const auth = require("../controllers/authController.js");
const app = require('express');
const { check, validationResult, query } = require("express-validator");
const router = app.Router();
require('express-group-routes');
module.exports = (router) => {
    router.group('/api', (router) => {

        router.get("/", (req,res) => {
            return res.status(200).send({ message: "Service Running" });
        });


        router.get("/users", (req, res) => {
            const errors = validationResult(req);
            if (!errors.isEmpty()) {
                return util.ResponseUtil.generateResponseJSON(res, 503, 'Error in validation', { errors: errors.mapped() });
            } else {
                auth.userInfo(req, res);
            }
        });

    });
}
    

  1. 当 运行 docker 容器时 docker run -it -p 3000:3000 service:latest

  2. 该应用程序是 运行,我得到 Server started ::: 1594299481981

  3. 我正在尝试 GET http://localhost:3000/api/

  4. 它returns我

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>Error</title>
</head>

<body>
    <pre>Cannot GET /api/</pre>
</body>

</html>

我试过的

express-group-routes 没有积极维护(4 年前)

它的 npm 站点 https://www.npmjs.com/package/express-group-routes 也没有 github 存储库!

尝试使用此代码段:

https://github.com/jrichardsz/nodejs-express-snippets/blob/master/01-hello-world.js

我在其中向您展示了一个基本的路线示例。

如果你想对你的路线进行分组,你可以使用这样的东西:

server.js

const app = require('express');
const AdminRoute = require ...
const UserRoute = require ...
....
AdminRoute.configure(app)
UserRoute.configure(app)

或者这个

  fs.readdirSync(`/some/folder/routes/`).forEach(function(file){
    var commandRequire = require(`/some/folder/routes/`+file);
    var command = new commandRequire();
  });

其中我从文件夹中读取js文件并动态实例化它们,所以你的server.js会更加减少:

const app = require('express');
const ScanRoutes = require ...
...
ScanRoutes.scan("routes/folder", app)