【问题标题】:Why isn't this displaying the ' admin' page?为什么不显示“管理”页面?
【发布时间】:2016-12-09 02:31:39
【问题描述】:

我正在阅读 MEAN MACHINE 书籍,并按照以下说明进行操作 路由节点应用程序 [pg - 36]

express.Router()⁴⁸ 充当迷你应用程序。你可以调用它的一个实例(就像我们为 Express 做的那样) 然后在其上定义路线。让我们看一个例子,以便我们确切地知道这意味着什么。添加 如果您愿意,请将此添加到您的“server.js”文件中。 在 server.js 内的 app.get() 路由下方,添加以下内容。我们将 1. 调用一个实例 2. 应用路由 3. 然后将这些路由添加到我们的主应用程序

因此,我复制粘贴了代码 [请参见下文] http://localhost:1337/admin 页面抛出错误说“无法获取/管理”

代码:

// load the express package and create our app
var express = require('express');
var app = express();
var path = require('path');

// send our index.html file to the user for the home page
app.get('/', function(req, res) {
    res.sendFile(path.join(__dirname + '/index.html'));
});

// create routes for the admin section
// get an instance of the router
var adminRouter = express.Router();
// route middleware that will happen on every request
// admin main page. the dashboard (http://localhost:1337/admin)
adminRouter.get('/', function(req, res) {
    res.send('I am the dashboard!');
});

// users page (http://localhost:1337/admin/users)
adminRouter.get('/users', function(req, res) {
    res.send('I show all the users!');
});

// posts page (http://localhost:1337/admin/posts)
adminRouter.get('/posts', function(req, res) {
    res.send('I show all the posts!');
    // apply the routes to our application
    app.use('/admin', adminRouter);
}); 

// start the server
app.listen(1337);
console.log('1337 is the magic port!');

【问题讨论】:

    标签: javascript node.js api express meanjs


    【解决方案1】:

    app.use('/admin', adminRouter); 行将 adminRouter 添加到主应用程序。

    你有那个该路由器上为/posts调用的函数。

    因此,它永远不会被调用。

    您需要将其向下移动,使其显示在});// start the server 之间

    【讨论】:

      【解决方案2】:
           adminRouter.get('/posts', function(req, res) {
           res.send('I show all the posts!');
      
          // apply the routes to our application
          app.use('/admin', adminRouter);
      
       }); 
      

      在中间件之外使用 app.use。

          adminRouter.get('/posts', function(req, res) {
            res.send('I show all the posts!');
          })
        // apply the routes to our application
          app.use('/admin', adminRouter);
      

      【讨论】:

        猜你喜欢
        • 2017-11-24
        • 1970-01-01
        • 2012-04-29
        • 2011-05-09
        • 2019-03-08
        • 1970-01-01
        • 2017-01-22
        • 2017-11-21
        • 1970-01-01
        相关资源
        最近更新 更多