我正在尝试使用 express 访问位于我的 public 文件夹中的文件。 我的文件结构是这样的
/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 文件夹内,因此您不需要将 app
文件夹包含在 express.static('app/public')
并使用 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">
关于javascript - 如何在 node.js express 中访问我的公用文件夹中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41291382/