繁体   English   中英

NodeJS设置通配符路由或url重写

[英]NodeJS setting up wildcard routes or url rewrite

我在使用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');
    });
}

启动应用程序(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);

我想要做的是:

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

我通过解析url来确定要返回的数据。

首先,路由器中间件已从Connect中删除,因此您可以使用Express或使您自己的路由器在未来更安全(请参阅此提交: https//github.com/senchalabs/connect/commit/2ca7ec3ff64cb7600bfd029233228236bf048671 )。

如果您选择使用Express,您可以传递路线的正则表达式(更多信息请访问: http//expressjs.com/guide.html#routing ),但我会使用类似的东西(针对您的具体情况) ):

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

暂无
暂无

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

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