我想问您如何使用mod_rewrite在node.js上重写url。connect-modrewrite的创建者准备了示例这里,但不幸的是,在express的情况下,这个示例无效,在目前的版本中,不推荐使用configure。
标准语法是:
var app = require('express')();
var http = require('http').Server(app);
app.get('/', function(req, res){
res.sendfile('index.html');
});
http.listen(3000, function(){
console.log('listening for clients on *:3000');
});我尝试将标准语法与connect-modrewrite结合起来,如下所示:
var app = require('express')();
var http = require('http').Server(app);
var modRewrite = require('connect-modrewrite');
app.get(modRewrite([
'^/test$ /index.html',
'^/test/\\d*$ /index.html [L]',
'^/test/\\d*/\\d*$ /flag.html [L]'
]), function(req, res){
res.sendfile('index.html');
});
http.listen(3000, function(){
console.log('listening for clients on *:3000');
});这会引发以下错误:
(...)node_modules/express/node_modules/path-to-regexp/index.js:34
.concat(strict ? '' : '/?')我被堵住了。如果有人有主意的话,我会很棒的。
发布于 2014-07-09 19:57:29
我得到了connect-modrewrite :)作者的一些支持,以下是解决方案:
var app = require('express')();
var http = require('http').Server(app);
app.use(modRewrite([
'^/test$ /index.html',
'^/test/\\d*$ /index.html [L]',
'^/test/\\d*/\\d*$ /flag.html [L]'
]));
app.get('/index.html', function(req, res){
res.sendfile('index.html');
});
http.listen(3000, function(){
console.log('listening for clients on *:3000');
});效果很好!干杯!
发布于 2015-08-01 14:18:14
这是我根据马立克的答案使用的。其想法是,快运非静态路线将不适用于这里。对于所有静态路由,您希望确保它们中的一些将保持不变,并且其中一些将被重写到另一个目的地,例如。在这里,如果不是来自样式、脚本、图像、字体和文件文件夹,我确保所有其他东西都进入了index.html。
但是,如果你已经设置了一条特快路线,“/城市”,它仍然会保持不变。
var modRewrite = require('connect-modrewrite');
app.use(modRewrite([
// express route has been taken care of, and won't enter here.
'^/styles/(.*)$ - [L]', // keep
'^/scripts/(.*)$ - [L]', // keep
'^/images/(.*)$ - [L]', // keep
'^/fonts/(.*)$ - [L]', // keep
'^/files/(.*)$ - [L]', // keep
'^/.*$ /index.html' // for whatever else, use index.html
//'^((?!api).)*$ /index.html' // for non-api routes, use index.html
]));
app.use(express.static(global.appRoot + config.www));https://stackoverflow.com/questions/24586568
复制相似问题