如何在 node.js express 中访问我的公共文件夹中的文件

cro*_*rod 5 javascript node.js express

我正在尝试使用 express访问位于我的公共文件夹中的文件。我的文件结构是这样的

/app
 -app.js
 /routes
  -index.js
 /public
  /images
   /misc
   -background.jpg
  /css
    -style.css
Run Code Online (Sandbox Code Playgroud)

我的app.js在端口3000上运行,

app.use(express.static('app/public'));
app.use(require('./routes/index'));
Run Code Online (Sandbox Code Playgroud)

index.js找不到background.jpgstyle.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;
Run Code Online (Sandbox Code Playgroud)

我正在查看文档,所以我不知道为什么这不起作用。

Aru*_*una 7

由于您的app.jspublic文件夹位于 app 文件夹内,因此您无需将该app文件夹包含在内express.static('app/public'),也可以path.resolve按如下方式使用,

var path = require('path');

app.use(express.static(path.resolve('./public')));
Run Code Online (Sandbox Code Playgroud)

另外,将href下面的值更改为href="/css/style.css"

<link rel="stylesheet" type="text/css"
  href="/css/style.css">
Run Code Online (Sandbox Code Playgroud)


小智 5

app.js 中需要路径模块:

var path=require('path');
Run Code Online (Sandbox Code Playgroud)

修改静态内容的中间件:

app.use(express.static(path.join(__dirname,'public')));
Run Code Online (Sandbox Code Playgroud)

像这样链接到你的CSS:

<link rel="stylesheet" type="text/css" href="/css/style.css">
Run Code Online (Sandbox Code Playgroud)