简体   繁体   English

为什么在Express中不能静态工作?

[英]Why doesn't work static in Express?

I have just started to learn nodejs and faced the problem that in Express framework i can't load simple HTML files. 我刚刚开始学习nodejs并遇到了Express框架中我无法加载简单HTML文件的问题。

My projects structure is like this: 我的项目结构如下:

结构体

In assets are two extra folders: js and css which contains files. 资产中有两个额外的文件夹: jscss ,其中包含文件。 My server.js file looks like this: 我的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/' returns /Sites/node_project/assets/ which is the exact location of files. config.ROOT_DIR + '/assets/'返回/Sites/node_project/assets/ ,这是文件的确切位置。 To be 100% sure i run ls /Sites/node_project/assets/ and it returns css js , but still when i open http://192.168.1.109:4935 i get only index.html with no js or css … If i try to open directly some file, for example css i get Cannot GET /assets/css/jquery.mobile.css 要100%确定我运行ls /Sites/node_project/assets/ ,它返回css js ,但是当我打开http://192.168.1.109:4935时,我仍然只得到index.html而没有jscss …如果我尝试直接打开某些文件,例如css我Cannot GET /assets/css/jquery.mobile.css

What i'm doing wrong? 我做错了什么?

UPDATE 更新

Found the solution, it should be like app.use('/assets', express.static(config.ROOT_DIR + '/assets/')); 找到解决方案,它应该像app.use('/assets', express.static(config.ROOT_DIR + '/assets/'));

Try something more like this: 尝试更多类似这样的方法:

/* 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]); 
});

Here is a good tutorial: http://www.mfranc.com/node-js/node-js-simple-web-server-with-express/ 这是一个很好的教程: http : //www.mfranc.com/node-js/node-js-simple-web-server-with-express/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM