如何在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.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
文件夹位于应用程序文件夹内,因此您无需在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">
- 用node.js显示错误
- Express +句柄上的Socket.io在https上不起作用
- 在express中,获取包含特殊字符的request.query
- Fullcalendar Angular / Node.JS http请求:TypeError:将循环结构转换为JSON(在Object.stringify处)
- 你如何dynamic地设置一个Jade模板的布局,以在Node.js / Express 3.0中进行扩展?
- find文档,并使用Node.JS Mongoose将值插入MongoDB中的数组
- 如何使用jsonp和node.js express
- node.js样板+最佳实践
- Node.js表示应用程序caching/缓慢页面加载(swig模板引擎)