Saturday 13 May 2017

Serving static files with Express

I've written a Node.js application using express. When I request /, I want to serve /public/app/index.html. This works. However, index.html includes two css and two js files, and the relative pathing breaks. The paths are set as such (in the HTML header) but when trying to obtain app.js and style.css, the (browser?) thinks to look at / because, of course, that's what is being served.

<link rel='stylesheet' href='/lib/lib.css'/>
<link rel='stylesheet' href='style.css'/>
<script type="application/javascript" src="/lib/lib.js"></script>
<script type="application/javascript" src="app.js"></script>

The reason why this is a problem to me that I use a build process for my HTML, and it was logical at the time to dump all built files into one folder (HTML, CSS, JS, images). That way a template HTML file could be used that always pointed to js and css within its own folder. I'm hoping I can avoid injecting scripts with relative pathing.

Folder structure

root/
├── public/
│   ├── lib/
|   |    ├── lib.js
|   |    └── lib.css
│   ├── app/
│   |    ├── index.html
│   |    ├── style.css
|   |    └── app.js
├── app.js
├── routes/
|     └── index.js

app.js

var app = express();
var server = app.listen(4100);
app.use(express.static(path.join(__dirname, 'public')));
// routes
var index = require('./routes/index');
app.use('/', index);

index.js

var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) {
    var path = 'index.html';
    var options = {
        root : './public/app/'
    };
    res.sendFile(path, options, function(err){
        console.log(err)
    });
});

module.exports = router;



via jozenbasin

No comments:

Post a Comment