【问题标题】:Binding a route to '/' is responding to all 404s in Express?将路由绑定到“/”是否响应 Express 中的所有 404?
【发布时间】:2013-09-19 08:49:22
【问题描述】:

您好,我是 node 新手,遇到 Express 路由问题。我正在尝试创建一个迷你 MVC 框架来创建测试项目并学习 node/noSQL。大多数代码都基于 Express 存储库中的 MVC 示例 (https://github.com/visionmedia/express/tree/master/examples/mvc)。除此之外,我还在此处的帮助下添加了可扩展控制器:How to create extendable controllers in ExpressJS

代码:https://github.com/monsterlane/node-runner

问题出在https://github.com/monsterlane/node-runner/blob/master/app/boot/index.js 第 33-43 行。

if ( key == 'index' && name == 'main' ) {
    method = 'get';
    path = '/';
}
else if ( key == 'index' ) {
    method = 'get';
    path = '/' + name;
}
else {
    throw new Error( 'unrecognized route: ' + name + '.' + key );
}

我在这个块中尝试做的是分配主控制器来响应 localhost/ 并分配每个其他控制器来响应 localhost/controller/。如果我将第 35 行更改为 /main(而不是 /),那么 404 将正确地通过引导并进入 app/index.js 中的错误处理程序:

// load controllers
require( './boot' )( app, { verbose: !module.parent } );

// assume "not found" in the error msgs is a 404
app.use( function( err, req, res, next ) {
    // treat as 404
    if ( ~err.message.indexOf( 'not found' ) ) return next( );

    // log it
    console.error( err.stack );

    // error page
    res.status( 500 ).render( '5xx' );
});

按原样使用代码,如果我转到任何无效的 URL、localhost/deep、localhost/doop 它们都返回主模块?出于某种原因,绑定到“/”似乎会使任何无效 URL 使用此路由?

关于我做错了什么有什么想法吗?谢谢!

【问题讨论】:

    标签: node.js model-view-controller express routes


    【解决方案1】:

    将 app.use 更改为 app.all 解决了该问题。有谁知道有什么区别吗?

    【讨论】:

    猜你喜欢
    • 2014-12-27
    • 2013-08-26
    • 1970-01-01
    • 2021-07-28
    • 2022-01-02
    • 2016-10-25
    • 1970-01-01
    • 2015-01-11
    • 2016-09-18
    相关资源
    最近更新 更多