在node.js Express框架中设置两个不同的静态目录

发布于 2024-11-06 06:54:02 字数 48 浏览 0 评论 0原文

是否可以?我想设置两个不同的目录来提供静态文件。假设 /public 和 /mnt

Is it possible? I would like to set up two different directories to serve static files. Let's say /public and /mnt

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

北音执念 2024-11-13 06:54:02

您还可以通过为 use() 指定附加(第一个)参数来设置将静态文件提供给 Web 的路径,如下所示:

app.use("/public", express.static(__dirname + "/public"));
app.use("/public2", express.static(__dirname + "/public2"));

这样您就可以在 Web 上获得两个不同的镜像目录您的本地目录,而不是在两个本地目录之间进行故障转移的 url 路径。

换句话说,URL 模式:

http://your.server.com/public/*

从本地目录 public 提供文件,同时:

http://your.server.com/public2/*

从本地目录 public2 提供文件。

顺便说一句,如果您不希望静态从服务器根目录而是从更合格的路径提供文件,这也很有用。

华泰

You can also set the path that static files will be served to the web from by specifying an additional (first) parameter to use() like so:

app.use("/public", express.static(__dirname + "/public"));
app.use("/public2", express.static(__dirname + "/public2"));

That way you get two different directories on the web that mirror your local directories, not one url path that fails over between two local directories.

In other words the URL pattern:

http://your.server.com/public/*

Serves files from the local directory public while:

http://your.server.com/public2/*

Serves files from the local directory public2.

BTW this is also useful if you don't want static to serve the files from the root of your server but rather from a more qualified path.

HTH

尘曦 2024-11-13 06:54:02

您还可以将目录“合并”为单个可见目录

目录结构

  • /static
  • /alternate_static

Code

app.use("/static", express.static(__dirname + "/static"));
app.use("/static", express.static(__dirname + "/alternate_static"));

静态和静态alternate_static 将像它们位于同一目录中一样提供服务。不过,请注意文件名破坏者。

You can also "merge" directories into a single visible directory

Directory Structure

  • /static
  • /alternate_static

Code

app.use("/static", express.static(__dirname + "/static"));
app.use("/static", express.static(__dirname + "/alternate_static"));

Both static and alternate_static will be served as if they were in the same directory. Watch out for filename clobbers, though.

帅冕 2024-11-13 06:54:02

一次中间件注入是不可能的,但您可以多次注入static中间件:

app.configure('development', function(){
    app.use(express.static(__dirname + '/public1'));
    app.use(express.static(__dirname + '/public2'));
});

说明

请参阅connect/lib/middleware/static.js#143

path = normalize(join(root, path));

options.root 是静止的root,您在 express.staticconnect.static 调用中定义,path 是请求路径。

详细了解 connect/lib/middleware/static.js# 154

  fs.stat(path, function(err, stat){
    // ignore ENOENT
    if (err) {
      if (fn) return fn(err);
     return ('ENOENT' == err.code || 'ENAMETOOLONG' == err.code)
       ? next()
       : next(err);

路径仅检查一次,如果找不到文件,则请求传递到下一个中​​间件。

Connect 2.x 的更新

对于 Connect 2.x,代码链接是不实际的,但仍然可以像以前一样使用多个静态中间件。

It's not possible by one middleware injection, but you can inject static middleware multiple times:

app.configure('development', function(){
    app.use(express.static(__dirname + '/public1'));
    app.use(express.static(__dirname + '/public2'));
});

Explanation

Look at connect/lib/middleware/static.js#143:

path = normalize(join(root, path));

There is options.root is static root, which you define in express.static or connect.static call, and path is request path.

Look more at connect/lib/middleware/static.js#154:

  fs.stat(path, function(err, stat){
    // ignore ENOENT
    if (err) {
      if (fn) return fn(err);
     return ('ENOENT' == err.code || 'ENAMETOOLONG' == err.code)
       ? next()
       : next(err);

Path checked only once, and if file not found request passed to next middleware.

Update for Connect 2.x

Links to code are inactual for Connect 2.x, but multiple static middleware usage are still posible as before.

生活了然无味 2024-11-13 06:54:02

我也遇到了同样的问题,但经过长时间的搜索这个任务后,我设法解决了它。

第 1 步:

在 /public 和 /mnt 路径名中提供静态文件

app.use('/public', express.static(path.join(__dirname, '<path_to_the_folder_you_want_to_serve_public>')));

app.use('/mnt', express.static(path.join(__dirname, '<path_to_the_folder_you_want_to_serve_mnt>')));

第 2 步:

我的计划是在单个 NodeJS 服务器中部署两个 Angular 客户端应用程序。

因此,我在两个 Angular 客户端应用程序上运行了“ng build”。

我将一个 dist 文件夹放在“/public”文件夹中,将另一个 dist 文件夹放在“/mnt”文件夹中。

第3步:

需要修改index.html,通过更改以下内容来显示公用文件夹内容,

<script src="./public/runtime.js" defer></script>
<script src="./public/polyfills.js" defer></script>
<script src="./public/styles.js" defer></script>
<script src="./public/vendor.js" defer></script>
<script src="./public/main.js" defer></script>

需要通过更改以下内容来修改index.html,以显示mnt文件夹内容,

<script src="./mnt/runtime.js" defer></script>
<script src="./mnt/polyfills.js" defer></script>
<script src="./mnt/styles.js" defer></script>
<script src="./mnt/vendor.js" defer></script>
<script src="./mnt/main.js" defer></script>

重要提示:根据静态文件夹服务路径更改.js 文件路径。

第 4 步:

在一条路径中,您可以为 public 提供服务,在另一条路径中,您可以为 mnt 提供服务。

app.get('/', function(req, res) => {
  res.sendFile(path.join(__dirname, '../public/dist/index.html'));
})

app.get('/', function(req, res) => {
  res.sendFile(path.join(__dirname, '../mnt/dist/index.html'));
})

现在你可以走了。运行&测试一下。

I also faced the same issue but I managed it to resolve it, after a long search for this quest.

Step 1:

Serve the static files in the pathnames of /public and /mnt

app.use('/public', express.static(path.join(__dirname, '<path_to_the_folder_you_want_to_serve_public>')));

app.use('/mnt', express.static(path.join(__dirname, '<path_to_the_folder_you_want_to_serve_mnt>')));

Step 2:

My plan was to deploy two Angular client apps in a single NodeJS server.

So I ran the 'ng build' on both Angular client apps.

I placed one of dist folder in '/public' folder and another dist folder in '/mnt'.

Step 3:

Need to modify the index.html by changing the following things to show the public folder content,

<script src="./public/runtime.js" defer></script>
<script src="./public/polyfills.js" defer></script>
<script src="./public/styles.js" defer></script>
<script src="./public/vendor.js" defer></script>
<script src="./public/main.js" defer></script>

Need to modify the index.html by changing the following things to show the mnt folder content,

<script src="./mnt/runtime.js" defer></script>
<script src="./mnt/polyfills.js" defer></script>
<script src="./mnt/styles.js" defer></script>
<script src="./mnt/vendor.js" defer></script>
<script src="./mnt/main.js" defer></script>

Important Note : Change the .js files path based on the static folder serving path.

Step 4:

In one path, you can serve public and on another you can serve mnt.

app.get('/', function(req, res) => {
  res.sendFile(path.join(__dirname, '../public/dist/index.html'));
})

app.get('/', function(req, res) => {
  res.sendFile(path.join(__dirname, '../mnt/dist/index.html'));
})

Now you are good to go. Run & Test it.

不必在意 2024-11-13 06:54:02
const express = require('express');
const path = require('path');
const pagesPath = path.join(__dirname, '/cheatsheet');
const cssPath = path.join(__dirname, '/stylesheet');
const port = process.env.PORT || 3000;

var app = express();

app.use("/cheatsheet" ,express.static(pagesPath));
app.use("/stylesheet",express.static(cssPath)); 

app.get('/',(request,response)=>{
    response.send('Hello CSS!!!');
  });

app.get('/bad',(request,response)=>{
response.send({error: 'Bad Request'});

});
app.listen(port, ()=> {
console.log(`Server is running on Port ${port}` );
console.log(__dirname);

});

// folder structure
/cheatsheet/index.html
/stylesheet/style.css
const express = require('express');
const path = require('path');
const pagesPath = path.join(__dirname, '/cheatsheet');
const cssPath = path.join(__dirname, '/stylesheet');
const port = process.env.PORT || 3000;

var app = express();

app.use("/cheatsheet" ,express.static(pagesPath));
app.use("/stylesheet",express.static(cssPath)); 

app.get('/',(request,response)=>{
    response.send('Hello CSS!!!');
  });

app.get('/bad',(request,response)=>{
response.send({error: 'Bad Request'});

});
app.listen(port, ()=> {
console.log(`Server is running on Port ${port}` );
console.log(__dirname);

});

// folder structure
/cheatsheet/index.html
/stylesheet/style.css
傾城如夢未必闌珊 2024-11-13 06:54:02

自定义中间件中使用 express.static

app.use(customMiddleware())

要在

const customMiddleware = function() {
    return function(req, res, next) {
        // do some dynamic code
        // or
        return express.static(__dirname + "/public")(req, res, next);
    }
}

To use express.static inside custom middleware:

app.use(customMiddleware())

where

const customMiddleware = function() {
    return function(req, res, next) {
        // do some dynamic code
        // or
        return express.static(__dirname + "/public")(req, res, next);
    }
}
如梦亦如幻 2024-11-13 06:54:02

我们可以在nodejs服务器中针对特定路由动态启用静态文件

app.use("/test", (req, res, next) => {
    if (req.session.isAuth === undefined) {
        let middleware = express.static(path.join(__dirname, "staticPages"));
        middleware(req, res, next);
    } else {
        next();
    }
});

we can dynamically enable static files in nodejs server with respect to perticular route

app.use("/test", (req, res, next) => {
    if (req.session.isAuth === undefined) {
        let middleware = express.static(path.join(__dirname, "staticPages"));
        middleware(req, res, next);
    } else {
        next();
    }
});
始于初秋 2024-11-13 06:54:02

使用 :dir 而不是 *

例如

this.app.use('/:microsite', express.static(path.resolve(process.cwd(), 'client/')))

use :dir instead of *

eg

this.app.use('/:microsite', express.static(path.resolve(process.cwd(), 'client/')))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文