【问题标题】:NodeJS w/Express eliminate Error: Cannot GET /xyzNodeJS w/Express 消除错误:无法获取 /xyz
【发布时间】:2014-07-22 01:20:58
【问题描述】:

我的问题是,如果用户在地址栏 www.example.com/xyz 键入,用户会收到错误无法获取 /xyz。我的问题是如何捕获“/”之后的所有 url 参数。

我认为解决方案可能是这样的。

app.get('CATCH ALL URLS except /', function (req, res){
     res.sendfile(__dirname + '/index.html');
});

【问题讨论】:

  • 您真的想捕获 / 之后的内容,还是只想设置一个默认的 GET 处理程序来发送 index.html

标签: node.js express routing routes


【解决方案1】:

这就是我为 express 设置路由的方式。

app.get('/', routes.site.index);

app.get('/terms', routes.terms.list);

app.post('/terms', routes.terms.create);

app.get('/terms/:id', routes.terms.show);
app.post('/terms/:id', routes.terms.edit);
app.del('/terms/:id', routes.terms.del);

/*Handling wrong urls*/
app.get("/*", routes.site.wrong);

:id 将在您的方法中以 req.params.id 的形式提供。

【讨论】:

    【解决方案2】:

    只需定义两个路由,第一个用于 /,第二个用于其余路径:

    app.get('/', function (req, res) {
        // Do something for /
    });
    
    app.get('*', function (req, res) {
        res.sendfile(__dirname + '/index.html');
    });
    

    【讨论】:

      猜你喜欢
      • 2012-10-31
      • 2023-03-19
      • 1970-01-01
      • 1970-01-01
      • 2018-07-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-14
      • 2020-03-26
      相关资源
      最近更新 更多