Matheus Fachini
Matheus Fachini

Reputation: 167

Conflict with express.js - Cannot get my static files

Hello, I'm using express.js to make a webapp to buy tickets. So I have a page that direct a person to a info about the party, however, when I try load the static files to this page, the express.js cannot get.

On console view I saw that a new directory, with name of the path for the url, is setting before of static folder.


My app.js file:

var express = require('express');
var path = require('path');
var teste = require('./db/teste.json')

var app = express();

var list = Object.keys(teste).map( (value) => teste[value]);

app.set('view engine', 'jade'); 
app.set('views', (__dirname +  '/views'));

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

app.get('/', function(req, res){
 res.render('index')
});

app.get('/login/', function(req, res){
 res.render('login')
});

app.get('/dash/:title?', function(req, res){
 var title = req.params.title;
 if(title === undefined){
  res.status(503);
  var isDash = true;
  res.render('dash', {db: list, isDash: isDash});
 }else{
  var festa = teste.title;
  res.render('party', {db: festa, isDash: isDash});
 }
});

The console view:

PS: Only happens in this page.

Thank you!

Upvotes: 0

Views: 789

Answers (1)

dmansfield
dmansfield

Reputation: 1128

Because the page is localhost:3000/dash/name-of-party, static resources that use relative URL will be referenced relative to that page, so, e.g.:

<img src="static/something.jpg">

Will be retrieved with a full url of: http://localhost:3000/dash/static/something.jpg. Instead you could use src="/static/something.jpg" (notice the leading slash) and it may work. Just to confirm this is the issue you could add:

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

Right after the existing line that maps static resources.

Upvotes: 1

Related Questions