mb_s88
mb_s88

Reputation: 392

script tags in Express

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.

Upvotes: 0

Views: 39

Answers (1)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123513

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:

./static/orbit/util.js

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/`

Upvotes: 2

Related Questions