简体   繁体   English

NodeJS Express定义自定义路由

[英]NodeJS Express defining custom routes

This is probably a really basic concept that I'm not understanding but in my NodeJS application I am trying to define a custom route. 这可能是一个我不理解的基本概念,但在我的NodeJS应用程序中,我试图定义一个自定义路由。

my directory structure is as follows 我的目录结构如下

/application
    /app.js
    /package.json
    /node_modules
    /public
    /routes
        /control
            /users.js
    /views
        /control
            /users.ejs

Which I am happy with because I want to keep the routes and views in a 1 to 1 relationship because I will eventually end up with something like 我很满意,因为我希望将路线和观点保持在1比1的关系中,因为我最终会得到像这样的东西

/application
    /app.js
    /package.json
    /node_modules
    /public
    /routes
        /control
            /users.js
            /system.js
        /tools
            /stock.js
            /report.js
    /views
        /control
            /users.ejs
            /system.ejs
        /tools
            /stock.ejs
            /report.ejs

So I don't want to end up with a /routes/index.js file with a hideous amount of routing code inside. 所以我不希望最终得到一个带有大量路由代码的/routes/index.js文件。

It seems to work while my app.js file is as follows 它似乎工作,而我的app.js文件如下

//==============================================================================
// setup
//==============================================================================

var express = require("express");
var path = require("path");

var app = express();
var port = 3000;
var message = null;

app.set("view engine", "ejs");

app.use(express.static(path.join(__dirname, "public")));

//==============================================================================
// routes
//==============================================================================

var users = require("./routes/control/users");
app.get("/", users.users);

//==============================================================================
// start server
//==============================================================================

app.listen(port, function() {

   message = "Server Started : Port " + port;
   console.log(message);

});

Although I can see this is going to end up looking like 虽然我可以看到这最终会看起来像

//==============================================================================
// setup
//==============================================================================

var express = require("express");
var path = require("path");

var app = express();
var port = 3000;
var message = null;

app.set("view engine", "ejs");

app.use(express.static(path.join(__dirname, "public")));

//==============================================================================
// routes
//==============================================================================

// control

var users = require("./routes/control/users");
app.get("/", users.users);

var system = require("./routes/control/system");
app.get("/", system.system);

// tools

var stock = require("./routes/tools/stock");
app.get("/", stock.stock);

var report = require("./routes/tools/report");
app.get("/", report.report);

//==============================================================================
// start server
//==============================================================================

app.listen(port, function() {

   message = "Server Started : Port " + port;
   console.log(message);

});

So I don't really want to have that many requires but doing it like the following doesn't seem to work and I'm not sure why 所以我真的不想要那么多要求,但是这样做就好像以下似乎没有用,我不知道为什么

// control

var control = require("./routes/control");

app.get("/", control.users.users);
app.get("/", control.system.system);

// tools

var tools = require("./routes/tools");

app.get("/", tools.stock.stock);
app.get("/", tools.report.report);

You can use the express Router object to chain your routes. 您可以使用快速路由器对象来链接您的路由。 Here's an example 这是一个例子

/app.js /app.js

var routes = require('./routes/index');

// as noted by Paul in the comments, 
// you could use `app.use(routes)` for simplicity
app.use('/', routes);

/routes/index.js /routes/index.js

var routes = require('express').Router();

routes.route('/test')
    .get(function (req, res) {
        res.send(req.originalUrl);
    });

routes.use('/control', require('./control/user'));

module.exports = routes;

/routes/control/user.js /routes/control/user.js

var routes = require('express').Router();

routes.route('/test')
    .get(function (req, res) {
        res.send(req.originalUrl);
    });

module.exports = routes;

So for the route defined in index.js, you'll need to send a GET request to /test while in user.js, you will need to send a GET request to /control/test to get a response. 因此,对于index.js中定义的路由,您需要在user.js中向/test发送GET请求,您需要向/control/test发送GET请求以获取响应。

This way all you need to include in the main js file, app.js in your case, is the main routes file, which is index.js under the routes directory. 这样你需要包含在主js文件中的所有内容,就是你的情况下的app.js,是主路由文件,它是routes目录下的index.js。 Either way, you will still need to do one require statement for each file that exports a router object. 无论哪种方式,您仍然需要为导出路由器对象的每个文件执行一个require语句。

When you say: 当你说:

var control = require("./routes/control");

Node will do the followings: Node将执行以下操作:

  1. Since you privided a relative path to require, it will search for a routes directory within the current folder and in that directory search for a control.js file. 由于您将相对路径保留为require,它将搜索当前文件夹中的路径目录,并在该目录中搜索control.js文件。 It can't find control.js file so then: 它找不到control.js文件,所以:
  2. Search for a control.json file. 搜索control.json文件。 but it also can't find that file. 但它也找不到该文件。 then: 然后:
  3. Search for a control directory . 搜索控制目录 It finds such a directory. 它找到了这样一个目录。 opens it and search for a package.json file to look into its main property. 打开它并搜索package.json文件以查看其主要属性。 but it also cant find such a file. 但它也找不到这样的文件。 then: 然后:
  4. Search for a index.js file but also there is no such a file 搜索index.js文件,但也没有这样的文件

By default when you give a folder path to require , it does not load .js files inside that folder automatically it looks for package.json file and if it's not there it loads index.js . 默认情况下,当您提供要求的文件夹路径时,它不会自动加载该文件夹中的.js文件,它会查找package.json文件,如果不存在,则会加载index.js ie It looks for an entry point. 即它寻找一个入口点。

So make an index.js in your control folder: 所以在你的控制文件夹中创建一个index.js

/routes
  /control
    /users.js
    /system.js
    /index.js

index.js: index.js:

module.exports = {
  users: require('./users');
  system: require('./system');
};

Do this also for your tools directory and your last approach should work. 这也适用于您的工具目录,您的上一个方法应该可行。

Note that you could consider using express.Router to manage routes. 请注意 ,您可以考虑使用express.Router来管理路由。

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

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