简体   繁体   中英

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.

My projects structure is like this:

结构体

In assets are two extra folders: js and css which contains files. My server.js file looks like this:

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. 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

What i'm doing wrong?

UPDATE

Found the solution, it should be like 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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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