【问题标题】:app.get is not working for base routeapp.get 不适用于基本路线
【发布时间】:2014-10-06 09:19:00
【问题描述】:

我是 node.js 的新手,我尝试通过这项技术创建一个新项目。我使用 express 框架,但一开始我遇到了一些麻烦。我已经通过解决方法解决了这个问题,但我对下一个行为有疑问: 我的 app.js

var express = require('express')
  , routes = require('./routes/index')
  , routes = require('./routes/login');

var app = module.exports = express.createServer(); 
console.log(app.env);
// Configuration

app.configure(function(){
  app.set('views', __dirname + '/views');
  app.set('view engine', 'ejs');
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(app.router);
  app.use(express.static(__dirname + '/public'));
});


app.configure('development', function(){
  app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

app.configure('production', function(){
  app.use(express.errorHandler());
});

// Routes

app.use( function(req, res, next) {
    if (req.url == '/') {
        res.render('index', { title: 'Express!' })
    } else {
        next();
    }
});
//app.get('/', routes.index);

app.get('/login', routes.login);


app.listen(3000, function(){
  console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
});

// Routes 块中,您可以看到 app.useapp.get。如果我尝试使用 app.get 而不是 app.use 我会收到错误 "cannot get /"。我试图将 index.html 文件放到我的公用文件夹中。但是我每次都得到这个文件的“/”路由,而不是 index.js 的渲染。

app.get('/login', routes.login); - 工作正常,但“/”路线有问题。我不想让我的代码处于这种状态,请帮助我理解这种行为。

提前致谢。

【问题讨论】:

  • 你是在重新声明routes,只需更改变量名。
  • 谢谢。但是如何写出漂亮的代码呢?我每次都要复制对: routes = require('./routes') -> app.get('/', routes.index); ....... routes1 = require('./routes/login') -> app.get('/login', routes1.login);等等……?
  • 您可以使用许多模块化模式。例如,您可能会将所有单独的路由包含在一个通用的 routes 模块中。

标签: javascript node.js express


【解决方案1】:

喜欢用户 PA。提到,您的代码永远找不到 / 网址的原因是因为您正在重新声明您的 routes 变量:

var express = require('express')
  , routes = require('./routes/index')  // first declaration of 'routes'
  , routes = require('./routes/login'); // re-declaration of 'routes'

这会使您的代码无法访问您的第一个路由声明(指向 /index 的声明),这就是您收到错误“无法获取 /”的原因,因为您的路由变量仅指向 ./routes/login。

有几种方法可以解决此问题以清理代码:

1.为不同的路线分配不同的变量:

var express = require('express')
    , index = require('./routes/index')  
    , login = require('./routes/login');

- 0R -

2。将多个函数放入路由文件中:

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~
// in your routes/index file

exports.index = function(req, res){
   res.render('index', { title: 'Index Page' });
};

exports.login = function(req, res){
   res.render('login', { title: 'Login Page' });
};


// ~~~~~~~~~~~~~~~~~~~~~~~~~~~
// in your app.js file

// import your 'routes' functions from your 'routes' file 
var express = require('express')
      , routes = require('./routes/')  


// now use your routes functions like this:
app.get('/', routes.index);
app.get('/login', routes.login);

- 或 -

在大型应用程序中,或为了更好的代码可维护性,您可能希望将不同的路由功能分解为不同的文件(而不是将所有路由功能放在一个文件中,如上面的示例),因此使用 express 默认以 setup 为例,他们将 user 函数和 index 函数放在 routes 文件夹中,如下所示:

routes /
   user.js
   index.js

然后,他们像这样设置他们的应用程序:

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

并像这样调用这些函数:

app.get('/', routes.index); // calls the "index" function inside the routes/index.js
app.get('/users', user.list); // calls the "list" function inside the routes/user.js file

希望这会有所帮助。

快速提示:app.use() 用于创建中间件,该函数将在您的应用程序中的每个请求上被调用,让开发人员可以访问请求对象 req 和响应对象 @ 987654332@,以及以某种方式更改或增强您的应用程序的能力。 “在请求中采取行动”的能力是一项强大的功能,它在您的原始示例中为您工作的原因是因为在调用 / 的请求时调用了您的 app.use() 中间件。 ,即使您的应用找不到/,在您重新声明routes 变量时丢失了,您仍在向/ 发出请求,您的app.use() 能够看到(因为每个请求都会调用中间件,即使是“坏”请求),所以您的中间件仍然看到对 / 的 [invalid] 请求,并且行为如下:

// This middleware will get called on every request, 
// even on the invalid request for '/'
app.use( function(req, res, next) {

    // this line of code will see that the 
    // request is for "/" and fire
    if (req.url == '/') {
        // the page now appears to render, because you are forcing the
        // res.render code inside of your middleware, which isn't always
        // recommended, but it is working for you in this example
        // because its the only place in your example that can do anything
        // when the '/' request is made
        res.render('index', { title: 'Express!' })
    } else {
        // this is common middleware design pattern, the next()
        // function tells the express framework to "move on to the next function"
        // in the middleware stack
        next();
    }
});

【讨论】:

  • 感谢您的详细解答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-03-04
  • 1970-01-01
  • 2019-06-24
  • 1970-01-01
  • 2023-03-27
  • 1970-01-01
  • 2020-05-16
相关资源
最近更新 更多