1

我真的很喜欢 PHP 在服务页面中提供的简单性,一切都基于文件系统。我想对 Node 做同样的事情。我尝试了一种像这样用于视图的路由设置,但破坏了我的公用文件夹:

//using express:
app.get('*', function(req, res) {
  file = req.params[0].substr(1, req.params[0].length);
  console.log('requesting: ' + file);
  res.render(file, {locals: {
    req: req,
    params: req.query
  }});
});

所以...

在 Node 中设置基于文件系统的/php 样式路由的最佳方法是什么?

4

2 回答 2

2

我认为我构建的正是您正在寻找的东西。我用它来提供.jade文件,显然你可以根据你的用例调整它。

var url = require('url');
var express = require('express');
var app = express.createServer();
var fs = require('fs');

app.set("view engine", "jade");

app.use(app.router);
app.use(express.static(__dirname + '/public'));

/**
 * Generic "get" attempts to route to known JADE files.
 * If no known JADE files, then we pass routing to next() (should be static).
 */
app.get('*', function(req, res, next) {

  var pathname = url.parse(req.url).pathname.toLowerCase(); // make matching case insenstive

  // First case: with no path name, render the default index.jade
  if(!pathname) {
    res.render('index', {});
  }
  // Second case: path ending in '/' points to a folder, use index.jade from that folder
  else if (pathname === '/' || pathname.charAt(pathname.length-1) === '/' ){
    res.render(__dirname + '/views' + pathname + 'index.jade', {});
  }
  // Third case: looks like an actual file, attempt to render
  else {
    // Attempt to find the referenced jade file and render that. Note 'views' is default path.
    fs.stat( (__dirname + "/views" + pathname + '.jade'), function(err, stats){
      // There was an error, the file does not exist pass control to the static handler
      if(err || !stats) {
        next();
      }
      // We found the file, render it.
      else{
        res.render(pathname.substring(1), {});
      }
    });

  }
});

app.listen(port);

请注意,那里应该有更多app.use()用于处理 cookie、解析正文等的语句。此外,第二个参数render始终为空。{layout: xyz}您可能希望使用需要进入呈现页面的内容或通用变量来填写此内容。

于 2012-04-30T20:02:29.907 回答
0

您可以使用 express.static()

举些例子:

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

app.configure(function(){
  app.use('/uploads', express.static(PATH_TO_UPLOAD_FOLDER));
});
于 2012-04-30T05:07:38.470 回答