简体   繁体   中英

NodeJS setting up wildcard routes or url rewrite

I have a simple route thing like this in node using connect (source/routes.js):

exports.routes = function(app) {
    app.get('/data', function(req, res, params) {
            res.writeHead(200, { 'Content-type': 'text/plain' });
            res.write('Authenticated: ' + connect.session.auth + '\n');
            res.end('app.get /data');
    });
}

Starting the app (app.js):

var routes = require('connect');
var routes = require('./source/routes');

var server = connect.createServer(
    connect.cookieParser(),
    connect.session({ secret: 'justmeknowsthis', cookie: { maxAge: config.data.sessionTimeout }}),
    connect.router(routes.routes)
);

server.listen(3000);

What I want to be able to do is:

app.get('/data*', function(...

I determine what data to return by parsing the url.

First of all, the router middleware has been removed from Connect, so you can either use Express or make your own router to be safer for the future ( see this commit: https://github.com/senchalabs/connect/commit/2ca7ec3ff64cb7600bfd029233228236bf048671 ).

If you choose to use Express, you can pass in a regular expression for the route (more info here: http://expressjs.com/guide.html#routing ), but I would use something like this instead (for your specific case):

app.get('/data/:type', function (req, res) {
  console.log('Received ' + req.params.type + ' data');
});

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