Search code examples
javascriptnode.jsexpressurl-routingstatic-files

Route looks for statics files in the wrong place


For some reason I have one particular route, /admins/:id, that looks for static files in /public/admins/ instead of /public/. This results in 404 errors and the js and css files not loading for this page. All other routes look for static files in /public/. I never changed the middleware for serving static files since I started coding the app, so I have no idea where the errant code could be.

For example, it's looking for /admins/stylesheets/bootstrap.min.css when it should be looking for /stylesheets/bootstrap.min.css.

app.js

var express = require('express');
var stormpath = require('express-stormpath');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

// include routes
var mainPage = require('./routes/mainPage');
var admins = require('./routes/admin');
var addAdmin = require('./routes/addAdmin');
var addDev = require('./routes/addDev');
var adminProfile = require('./routes/adminProfile');
var devs = require('./routes/dev');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// routes
app.use('/', mainPage);
app.use('/api/admins', admins);
app.use('/addAdmin', addAdmin);
app.use('/addDev', addDev);
app.use('/admins', adminProfile);
app.use('/api/devs', devs);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

module.exports = app;

adminProfile.js

var Admin = require('../models').sequelize.models.Admin;
var express = require('express');
var router = express.Router();

router.get('/:id', function(req, res, next) {
    Admin.findOne({
        where: {
            id: req.params.id,
        }
    })
    .then(function(admin) {
        if(!admin) {
            var err = new Error('Not Found');
            err.status = 404;
            res.render('error', { error: err });
        } else
            res.render('adminProfile', { admin: admin }); 
    });
});

module.exports = router;

Solution

  • What does your <link> tag look like in the HTML? You may need to anchor the href attribute by putting a / at the beginning, like so:

    <link type="text/css" href="/stylesheets/bootstrap.min.css" />
    

    That will create a root-relative URL. See Having links relative to root?