使用ExpressJS重写URL

时间:2013-05-16 05:11:35

标签: url-rewriting express

我想在ExpressJS网站上重写我的网址。我已经使用过这个插件https://github.com/joehewitt/express-rewrite,但它不起作用......

然而,我可能犯了一个错误......

我的app.js文件:

var express = require('express')
    , index = require('./routes/index.js')
    , admin = require('./routes/admin.js')
    , contact = require('./routes/contact.js')
    , posts = require('./routes/posts.js')
    , http = require('http')
    , path = require('path')
    , hash = require('./auth').hash
    , db = require('./models')
    , favicons = require('connect-favicons')
    , rewriter = require('express-rewrite');


var app = express();

app.configure(function () {
    app.set('port', process.env.PORT || 3000);
    app.set('views', __dirname + '/views');
    app.set('view engine', 'jade');
    app.use(express.favicon(__dirname + '/public/images/FAVICON.ico'));
    app.use(favicons(__dirname + '/public/images/apple-touch-icon.png'));
    app.use(express.logger('dev'));
    app.use(express.bodyParser());
    app.use(express.static(path.join(__dirname, 'public')));
    app.use(express.cookieParser());
    app.use(express.cookieSession({
            secret: 'SECRET',
            cookie: { access: false }
        })
    );
    app.use(rewriter);
    app.use(app.router);
    app.use(function(req, res, next){
        res.render('404.jade', {
            title: "404 - Page Not Found",
            showFullNav: false,
            status: 404,
            url: req.url
        });
    });
});

app.configure('development', function () {
    app.use(express.errorHandler());
});

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

app.get('/toto', rewriter.rewrite('/heytoto'));

db.sequelize.sync().complete(function(err) {
    if (err) {
        throw err
    } else {
        http.createServer(app).listen(app.get('port'), function(){
            console.log('Express server listening on port ' + app.get('port'))
        })
    }
});

我的错误讯息:

Express
500 TypeError: Object function app(req, res){ app.handle(req, res); } has no method 'match'
at Object.rewriter [as handle] (/Users/anthonycluse/Sites/Anthony-Cluse-Express/node_modules/express-rewrite/rewrite.js:3:26)
at next (/Users/anthonycluse/Sites/Anthony-Cluse-Express/node_modules/express/node_modules/connect/lib/proto.js:199:15)
at Object.cookieSession [as handle] (/Users/anthonycluse/Sites/Anthony-Cluse-Express/node_modules/express/node_modules/connect/lib/middleware/cookieSession.js:113:5)
at next (/Users/anthonycluse/Sites/Anthony-Cluse-Express/node_modules/express/node_modules/connect/lib/proto.js:199:15)
at Object.cookieParser [as handle] (/Users/anthonycluse/Sites/Anthony-Cluse-Express/node_modules/express/node_modules/connect/lib/middleware/cookieParser.js:60:5)
at next (/Users/anthonycluse/Sites/Anthony-Cluse-Express/node_modules/express/node_modules/connect/lib/proto.js:199:15)
at resume (/Users/anthonycluse/Sites/Anthony-Cluse-Express/node_modules/express/node_modules/connect/lib/middleware/static.js:60:7)
at SendStream.error (/Users/anthonycluse/Sites/Anthony-Cluse-Express/node_modules/express/node_modules/connect/lib/middleware/static.js:73:37)
at SendStream.EventEmitter.emit (events.js:126:20)
at SendStream.error (/Users/anthonycluse/Sites/Anthony-Cluse-Express/node_modules/express/node_modules/send/lib/send.js:147:51)

5 个答案:

答案 0 :(得分:34)

所以我有同样的问题。我编写了一个在浏览器上使用历史记录API的应用程序,我想将所有非静态URL重写回index.html。所以对于我做的静态文件:

app.configure(function() {
  app.use('/', express.static(__dirname + '/'));
});

但是对于历史API生成的路径我做了:

app.get('*', function(request, response, next) {
  response.sendfile(__dirname + '/index.html');
});

这意味着任何不是/中的文件或目录的请求(例如历史API生成的URL)都不会被重写或重定向,而是index.html文件将服务,然后所有JS路由魔术。

希望这与您正在寻找的内容相近?

答案 1 :(得分:28)

您可以在到达要使用的处理程序之前重写URL。

app.use(function(req, res, next) {
   if (req.url === '/toto') {
     req.url = '/heytoto';
   }
   next();
});

app.get('/heytoto', ...);

我使用similar method来使用正则表达式重写URL。

答案 2 :(得分:4)

在没有response.sendfile(..)的情况下工作的解决方案是使用在app.use(express.static(..))之前插入的重写中间件:

// forward all requests to /s/* to /index.html

app.use(function(req, res, next) {

  if (/\/s\/[^\/]+/.test(req.url)) {
    req.url = '/index.html';
  }

  next();
});

// insert express.static(...)

这样,expressjs可以正确识别重写。然后,static中间件将负责提供文件。

答案 3 :(得分:0)

您可以使用if条件检查网址,然后使用app.redirect重定向到某个网址。

答案 4 :(得分:-2)

试试这个:

app.get('/toto', function(req, res) {
  res.redirect('/heytoto');
});