首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在node.js Express框架中设置两个不同的静态目录

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

Stack Overflow用户
提问于 2011-05-12 12:53:58
回答 4查看 65.8K关注 0票数 108

有可能吗?我想设置两个不同的目录来提供静态文件。比方说/public和/mnt

EN

回答 4

Stack Overflow用户

发布于 2012-09-29 06:51:39

您还可以通过为use()指定一个额外的(第一个)参数来设置静态文件提供到web的路径,如下所示:

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

这样你就可以在网络上得到两个不同的目录来镜像你的本地目录,而不是两个本地目录之间故障转移的一个url路径。

换句话说,URL模式:

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

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

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

提供本地目录public2中的文件。

顺便说一下,如果您不想让static从服务器的根目录提供文件,而是从一个更合格的路径提供文件,那么这也很有用。

HTH

票数 164
EN

Stack Overflow用户

发布于 2018-09-27 05:45:12

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
票数 1
EN

Stack Overflow用户

发布于 2022-02-28 11:58:20

要在自定义中间件中使用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);
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5973432

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档