如何在node.js 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.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; 

我正在通过文档,所以我不知道为什么这是行不通的。

由于您的app.jspublic文件夹位于应用程序文件夹内,因此您无需在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中需要path模块:

 var path=require('path'); 

修改静态内容的中间件:

 app.use(express.static(path.join(__dirname,'public'))); 

链接到你的CSS是这样的:

 <link rel="stylesheet" type="text/css" href="/css/style.css">