简体   繁体   English

NodeJS w / Express消除错误:无法获取/ xyz

[英]NodeJS w/Express eliminate Error: Cannot GET /xyz

my problem is, if an user type to the adress bar www.example.com/xyz, the user got the error Cannot get /xyz. 我的问题是,如果用户在地址栏www.example.com/xyz上键入内容,则该用户收到错误消息“无法获取/ xyz”。 My question is how I can catch all the url params after "/". 我的问题是如何捕获“ /”后的所有url参数。

I thought that the solution could have something like this. 我以为解决方案可以有这样的东西。

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

Just define two routes, the first for / and the second for the rest: 只需定义两个路由,第一个用于/,第二个用于其他路由:

app.get('/', function (req, res) {
    // Do something for /
});

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

This is how I set up my routing for 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 will be available as req.params.id in your method. :id将在您的方法中作为req.params.id提供。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM