Mo Kargas
Mo Kargas

Reputation: 980

Node.js & Express: Static assets on dynamic routes aren't found

Bit stumped on how Node.js serves static assets. I'm using the latest Express, EJS, and Node. I have the following route in my app (Some code removed for brevity's sake, there are other routes without parameters). I've searched S.O. for similar questions, but feel my question is possibly different due to having two parameters.

app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));
    ...
    app.get('/:userid?/:catid?', function(req, res){
    ... some db queries here ...
        res.render('pages/listing',{
            siteConfig: nconf.get("siteConfig"),
            pageTitle: pageTitle,
            results:dbResults
       });
    }

In my EJS view templates, I have asset paths like the following:

<img src="/images/static_logo.png" />
<script src="/bower_components/modernizr/modernizr.js"></script>
<link rel="stylesheet" href="/css/app.min.css" />

The problem occurs when I pass both id's to this route, let's say localhost/763/201, my static assets appear do not render. All assets begin with the path http://localhost/763/css/style.css (Only the first ID). Ideally I want it to point to http://localhost/css/style.css regardless of the route.

I have tried removing the leading slash in the EJS files, using res.sendfile, and also hard-coding the assets as completely absolute paths, but the first and second options don't work, and the third option is not ideal.

Upvotes: 2

Views: 2054

Answers (1)

Michael Blankenship
Michael Blankenship

Reputation: 1669

Just noting that my own project's code includes the following without an initial slash before public:

app.use(express.static(path.join(__dirname, 'public')));

It might be worth a try to drop that initial slash in yours and try it.

Upvotes: 3

Related Questions