0

教程:我想通过 localhost 打开一个文件,但我不知道我必须在浏览器中输入哪个路径。是 localhost,我的 server.js 所在的位置吗?(对不起,我是编程和节点的新手)

教程代码

var path = require('path'),
    fs = require('fs');

require('http').createServer(function(req, res) {
  var file = path.normalize(req.url);

  console.log(file);

  path.exists(file, function(exists) {
    if (exists) {
      fs.stat(file, function(err, stat) {
        var rs;

        if (err) { throw err; }
        if (stat.isDirectory()) {
          res.writeHead(403);
          res.end('Forbidden');
        } else {
          rs = fs.createReadStream(file);
          res.writeHead(200);
          rs.pipe(res);
        }
      });
    } else {
      res.writeHead(404);
      res.end('Not found');
    }
  })
}).listen(4000);
4

1 回答 1

2

request.url通常/something/like/an/absolute/path,除非您从 HTTP 代理客户端(添加http://...前缀request.url)获取请求或发出一些自定义 HTTP 请求。

无论如何path.normalize只需要照顾..And .s。您的代码将允许任何人访问您计算机上的任何文件(可由node运行进程的帐户访问)。

更好/更安全的做法是加入__dirnamedecodedrequest.url并检查解析的路径是否以您要提供静态内容的目录的绝对路径(带有尾随路径分隔符)开头:

var scriptDir = path.resolve(__dirname + path.sep + "static" + path.sep),
    requestPath = decodeURIComponent(request.url);
requestPath = path.resolve(path.join(__dirname, "static", requestPath));
if (requestPath.indexOf(scriptDir) === 0) {
    // serve the file
} else {
    response.writeHead(403);
    response.end(http.STATUS_CODES[403]);
}

现在,如果您要求说,http://localhost:4000/index.html它应该提供位于/path/to/your/node/app/dir/static/index.html

于 2013-03-16T05:37:40.130 回答