javascript - app.get 不适用于基本路线

标签 javascript node.js express

我绝对是 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 block 中,您可以看到app.useapp.get。如果我尝试使用 app.get 而不是 app.use,我会收到错误“cannot get/”。我尝试将index.html 文件放入我的公共(public)文件夹中。但是fot“/”路线我每次都会得到这个文件,而不是index.js的渲染。

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

提前致谢。

最佳答案

喜欢用户 PA。提到的,您的代码从未找到 / url 的原因是因为您正在重新声明您的路由变量:

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 默认值以设置为例,他们将其 user 函数和 index 函数放置在路由文件夹中,如下所示:

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 和响应对象 res,以及以某种方式更改或增强应用程序的能力。 “在请求中间执行操作”的能力是一个强大的功能,它在原始示例中为您工作的原因是因为您的 app.use() 中间件在以下情况下被调用:即使您的应用无法找到 // 的请求仍被调用,当您重新声明 routes 变量时,该请求已丢失,您仍在向 / 发出请求,您的 app.use() 能够看到该请求(因为每个请求都会调用中间件,即使是“坏”请求),因此您的中间件仍然看到对 / 的[无效]请求,并按如下方式操作:

// 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();
    }
});

关于javascript - app.get 不适用于基本路线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26213210/

相关文章:

javascript - 添加到 Canvas 后更改文本

node.js - "npm install"触发grunt任务?

node.js - IE 中未定义“代理”

node.js - 你能用jade只渲染你的html的动态部分...而不弄乱你的html的其余部分吗

node.js - NodeJs 应用程序上的多个可选路由和 2 个处理程序

javascript - 通过 JS 函数打开 JqueryMobile Dialog

javascript - 在 Javascript 中检查数组中元素的类型

javascript - 为什么 Google ReCaptcha v2 复选框会在移动设备上超过 5 分钟的空闲时间后中断?

javascript - 使用导出模块将多个参数传递给 NodeJS 回调

node.js - 如何在nodejs中使用我服务器的域发送电子邮件