使用快递提供静态文件的最简单方法是什么? [英] What's the simplest way to serve static files using express?

查看:87
本文介绍了使用快递提供静态文件的最简单方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  var app = require('express')(),
server = require('http')。createServer(app),
fs = require('fs');
server.listen(80);

path =/ Users / my / path /;

var serve_files = {};
[myfile1.html,myfile2.html,myfile3.html] forEach(function(file){
serve_files [/+ file] = fs.readFileSync(path +文件utf8);
});

app.use(function(req,res){
if(served_files [req.path])
res.send(files [req.path]);
});

正确的方法是什么?

解决方案

Express有一个内置的中间件。它是连接的一部分,表达是基于的。中间件本身使用发送

  //只需通过`use` 
app.use(express.static(yourpath))将中间件添加到您的应用程序堆栈中;

在回答您的评论时,否,无法手动选择文件。虽然默认情况下,中间件将忽略以为前缀的文件夹,例如,名为 .hidden 的文件夹将不会投放



要手动隐藏文件或文件夹,您可以在 static 之前插入自己的中间件,以过滤掉请求到达以下内容将无法从名为隐藏的文件夹中提供任何文件

 应用程序.use(function(req,res,next){
if(/\h/hidden\/*/.test(req.path)){
return res.send(404,Not找到); //或403,etc
};
next();
});
app.use(express.static(__ dirname +/ public));


I'm using a rather ugly approach:

var app = require('express')(),
    server = require('http').createServer(app),
    fs = require('fs');
server.listen(80);

path = "/Users/my/path/";

var served_files = {};
["myfile1.html","myfile2.html","myfile3.html"].forEach(function(file){
    served_files["/"+file] = fs.readFileSync(path+file,"utf8");
});

app.use(function(req,res){
    if (served_files[req.path]) 
        res.send(files[req.path]);
});

What's the proper way to do it?

解决方案

Express has a built in middleware for this. It's part of connect, which express is built on. The middleware itself uses send.

// just add the middleware to your app stack via `use`
app.use(express.static(yourpath));

In answer to your comment, no, there is no way to manually select files. Though by default the middleware will ignore folders prefixed with ., so for example a folder named .hidden would not be served.

To hide files or folders manually, you could insert your own middleware before static to filter out paths before the request reaches it. The following would prevent serving any files from folders named hidden:

app.use(function(req, res, next) {
  if (/\/hidden\/*/.test(req.path)) {
    return res.send(404, "Not Found"); // or 403, etc
  };
  next();
});
app.use(express.static(__dirname+"/public"));

这篇关于使用快递提供静态文件的最简单方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆