[英]Why doesn't work static in Express?
我剛剛開始學習nodejs
並遇到了Express
框架中我無法加載簡單HTML文件的問題。
我的項目結構如下:
資產中有兩個額外的文件夾: js
和css
,其中包含文件。 我的server.js
文件如下所示:
module.exports.start = function(config) {
var express = require(config.MODULES_DIR + 'express'),
app = express(),
http = require('http'),
server = http.createServer(app),
io = require(config.MODULES_DIR + 'socket.io').listen(server),
fs = require('fs'),
path = require('path');
server.listen(config.APP_PORT);
// Setting static files dir to load it automatically
app.use(express.static(config.ROOT_DIR + '/assets/'));
console.log(config.ROOT_DIR + '/assets/');
app.get('/', function (req, res) {
res.sendfile(dir + 'index.html');
});
}
config.ROOT_DIR + '/assets/'
返回/Sites/node_project/assets/
,這是文件的確切位置。 要100%確定我運行ls /Sites/node_project/assets/
,它返回css js
,但是當我打開http://192.168.1.109:4935
時,我仍然只得到index.html
而沒有js
或css
…如果我嘗試直接打開某些文件,例如css我Cannot GET /assets/css/jquery.mobile.css
我做錯了什么?
更新
找到解決方案,它應該像app.use('/assets', express.static(config.ROOT_DIR + '/assets/'));
嘗試更多類似這樣的方法:
/* serves all the static files */
app.get(/^(.+)$/, function(req, res){
console.log("Static file request for: " + req.params);
res.sendfile( __dirname + "/assets" + req.params[0]);
});
這是一個很好的教程: http : //www.mfranc.com/node-js/node-js-simple-web-server-with-express/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.