Mihir
Mihir

Reputation: 8734

Scripts and css files not loading with jade + node js

I am learning mean stack development. I am using working out with some examples. I am trying to load my css files and javascript files in the jade file. files are appearing in the console --> Sources. But all the css files are loading with empty data and all the js files are loading with html data. enter image description here enter image description here enter image description here

I am having my server.js like this

var express = require("express");
var stylus = require("stylus");
var logger = require("morgan");
var bodyParser = require("body-parser");

var env = process.env.NODE_ENV = process.env.NODE_ENV || 'development';

var app = express();
function compile(str,path) {
    return stylus(str).set('filename', path);
}
app.set('views', __dirname + '/server/views');
app.set('view_engine', 'jade');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: false
}));
app.use(stylus.middleware({
    src: __dirname + '/public',
    compile:compile
}));
//defining routes
app.get('*', function (req,res) {
    res.render('index.jade');
});

var port = 3030;
app.listen(port);
console.log('starting listening....');

How to load the files properly in this scenario?

Upvotes: 0

Views: 988

Answers (1)

robertklep
robertklep

Reputation: 203231

The requests for client side resources are not being handled by anything in your app, which means they get handled by your "catch-all" handler (app.get('*', ...)), which returns HTML (which explains why you are seeing HTML being returned for jQuery, for instance).

You want to use a static file handler in your app to handle those requests:

app.use(express.static(__dirname));

The __dirname argument points to the directory that holds your client side resources files, so you may need to change this.

Also, make sure that you add this line above your catch-all handler, otherwise the requests will still be handled by that instead of the static file handler.

Upvotes: 1

Related Questions