简体   繁体   中英

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. My question is how I can catch all the url params after "/".

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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