[英]How to access files in my public folder in node.js express
我正在尝试使用 express 访问位于我的公用文件夹中的文件。 我的文件结构是这样的
/app
-app.js
/routes
-index.js
/public
/images
/misc
-background.jpg
/css
-style.css
我的app.js在端口3000上运行,
app.use(express.static('app/public'));
app.use(require('./routes/index'));
index.js找不到background.jpg或style.css
router.get('/',function(req,res){
res.send(`
<link rel="stylesheet" type="text/css"
href="css/style.css">
<h1>Welome</h1>
<img
src="/images/misc/background.jpg"
style="height:300px;"/>
<p>some text</p>`);
});
module.exports = router;
我正在看文档,所以我不知道为什么这不起作用。
由于您的app.js
和public
文件夹位于app文件夹中,因此您无需在express.static('app/public')
包含app
文件夹,也可以使用如下的path.resolve
,
var path = require('path');
app.use(express.static(path.resolve('./public')));
另外,将下面的href
值更改为href="/css/style.css"
,
<link rel="stylesheet" type="text/css"
href="/css/style.css">
在app.js中需要路径模块:
var path=require('path');
修改静态内容的中间件:
app.use(express.static(path.join(__dirname,'public')));
链接到你的CSS这样:
<link rel="stylesheet" type="text/css" href="/css/style.css">
显然是一个老问题,已得到充分回答,但这里是如何使其在不同的路径上可用
app.use('/u/profileImg/', express.static('./userCreated/profileImg/'));
其中第一个参数是 Web 可访问路径,第二个参数是文件夹的位置。
你也可以这样做
app.use('/u/', express.static('./userCreated/'));
和/u/profileImg/
以及/userCreated/
的其他内容仍然可用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.