nodejs相当于.htaccess

Gla*_*ats 15 .htaccess node.js

是否可以构建这样的代码node.js

<IfModule mod_rewrite.c>
     RewriteEngine on

     RewriteCond% {REQUEST_URI}! / (View) / [NC]
     RewriteCond% {REQUEST_FILENAME}!-F
     RewriteRule ^ (. *) $ Index.html [L, QSA]

</IfModule>
Run Code Online (Sandbox Code Playgroud)

url显示路由不是"查看",文件也不存在然后写index.html.

使用像express或的东西connect

更新:我需要一个正则表达式!/(view)/的路线expressnode.js.

小智 18

你有没有尝试过:

  1. 服务静力学
  2. 捕获/查看URL
  3. 赶上其他一切

    app.configure(function(){
      app.use(express.static(__dirname+'/public')); // Catch static files
      app.use(app.routes);
    });
    
    // Catch /view and do whatever you like
    app.all('/view', function(req, res) {
    
    });
    
    // Catch everything else and redirect to /index.html
    // Of course you could send the file's content with fs.readFile to avoid
    // using redirects
    app.all('*', function(req, res) { 
      res.redirect('/index.html'); 
    });
    
    Run Code Online (Sandbox Code Playgroud)

要么

  1. 服务静力学
  2. 检查URL是否为/ view

    app.configure(function(){
      app.use(express.static(__dirname+'/public')); // Catch static files
      app.use(function(req, res, next) {
        if (req.url == '/view') {
          next();
        } else {
          res.redirect('/index.html');
        }
      });
    });
    
    Run Code Online (Sandbox Code Playgroud)

要么

  1. 像往常一样抓住静力学
  2. 抓住/查看

    app.configure(function(){
      app.use(express.static(__dirname+'/public')); // Catch static files
      app.use(app.routes);
    });
    
    app.get(/^(?!\/view$).*$/, function(req, res) {
      res.redirect('/index.html');
    });
    
    Run Code Online (Sandbox Code Playgroud)

  • 谁能解释一下这里发生了什么? (4认同)

Gla*_*ats 5

最终的结构是:

var express = require('express'), url = require('url');

var app = express();
app.use(function(req, res, next) {
    console.log('%s %s', req.method, req.url);
    next();
});
app.configure(function() {
    var pub_dir = __dirname + '/public';
    app.set('port', process.env.PORT || 8080);
    app.engine('.html', require('ejs').__express);
    app.set('views', __dirname + '/views');
    app.set('view engine', 'html');
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    app.use(express.cookieParser());
    app.use(express.static(pub_dir));
    app.use(app.router);
});
app.get('/*', function(req, res) {
    if (req.xhr) {
        var pathname = url.parse(req.url).pathname;
        res.sendfile('index.html', {root: __dirname + '/public' + pathname});
    } else {
        res.render('index');
    }
});

app.listen(app.get('port'));
Run Code Online (Sandbox Code Playgroud)

谢谢大家。PD:使用模块 ejs 渲染 html