首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Node.js连接--结合快件的莫德写

Node.js连接--结合快件的莫德写
EN

Stack Overflow用户
提问于 2014-07-05 12:45:28
回答 2查看 1.2K关注 0票数 0

我想问您如何使用mod_rewrite在node.js上重写url。connect-modrewrite的创建者准备了示例这里,但不幸的是,在express的情况下,这个示例无效,在目前的版本中,不推荐使用configure

标准语法是:

代码语言:javascript
复制
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结合起来,如下所示:

代码语言:javascript
复制
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');
});

这会引发以下错误:

代码语言:javascript
复制
(...)node_modules/express/node_modules/path-to-regexp/index.js:34
.concat(strict ? '' : '/?')

我被堵住了。如果有人有主意的话,我会很棒的。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-07-09 19:57:29

我得到了connect-modrewrite :)作者的一些支持,以下是解决方案:

代码语言:javascript
复制
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');
});

效果很好!干杯!

票数 0
EN

Stack Overflow用户

发布于 2015-08-01 14:18:14

这是我根据马立克的答案使用的。其想法是,快运非静态路线将不适用于这里。对于所有静态路由,您希望确保它们中的一些将保持不变,并且其中一些将被重写到另一个目的地,例如。在这里,如果不是来自样式、脚本、图像、字体和文件文件夹,我确保所有其他东西都进入了index.html。

但是,如果你已经设置了一条特快路线,“/城市”,它仍然会保持不变。

代码语言:javascript
复制
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));
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24586568

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档