script tags in Express

- 1 answer


I have an index.html that has a couple script tags, but they are all returning 404 errors, and I can't figure out how to fix it. Currently they are in the top directory and referenced as such. e.g. <script type="text/javascript" src="./util.js"></script>.

I tried using require('./file.js'); but it would seem to me that this is not what I want. Would this not give me access only in the backend? It needs to be served with the html.




The root path that's given to express.static() is the directory that Express will begin at to match files on disk.

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

That path also won't be part of the URL. It's combined with the req.path in a manner similar to:

var rootPath = 'orbit'; // from `express.static('orbit')`

console.log(path.join(rootPath, req.path));
// 'orbit/orbit/util.js'

Note that orbit appears twice and static is missing, compared to the path in your comment:


Or, with the path suggested above:

var rootPath = path.join(__dirname, 'static');

console.log(path.join(rootPath, req.path));
// "/path/to/your/application/static/orbit/util.js"

// assuming `__dirname` is `/path/to/your/application/`