0

I have the following code, for example, throughout my template files:

<link href="http://localhost:3000/css/bootstrap.min.css" rel="stylesheet">

This forces me to change the IP address from http://localhost:3000 to the web server IP address whenever I launch the website. As you can imagine, there are a lot of template files for the whole site. I have written scripts that can search-and-replace the IP instances in the project's template files and I'd like to avoid that if I can.

I'd like to keep the following format:

<link href="css/bootstrap.min.css" rel="stylesheet">

Notice it is independent of the origin. I'd hope there was middlewear that Express could use the current location of the server to serve the files.

I am currently using this code in my server.js file:

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

And works great if I specify the host in the template files. I haven't found any resources online that do what I want to do easily.

Dan
  • 1,812
  • 3
  • 13
  • 27

2 Answers2

1

If the header is a template file, why don't you pass the full url as a variable to the template? You can construct the url at app level by something like this:

var baseUrl = req.protocol + '://' + req.get('host');

and pass baseUrl to your header template and prefix the paths at run-time.

Arbel
  • 30,599
  • 2
  • 28
  • 29
  • This solution is practical and exceptionally effective. **edit:** For future developers: `req.get('host')` also includes the port and colon in the url returned string. No need to append it. Use exactly as Arbel prescribed. – Dan Mar 29 '16 at 01:37
0

Try:

href="http://localhost:3000/v1/public/css/bootstrap.min.css" rel="stylesheet"

or relative:

href="./v1/public/css/bootstrap.min.css" rel="stylesheet"

Your static folder is the folder path where the static resources will be served.

Aleksandrenko
  • 2,987
  • 6
  • 28
  • 34