Reputation: 853
I use express that returns me some html page:
app.get('/', function(req, res){
return res.sendFile(path.resolve(__dirname + '/views/index.html'));
});
That index.html
contains a bunch of scripts in the tag <script></script>
.
I would like to move it to an external file like this:
<script src="./indexScripts.js"></script>
However it doesn't work and returns the following errors:
GET http://.../indexScripts.js net::ERR_ABORTED
GET http://.../indexScripts.js 404 (Not Found)
Would you have any clue on what I should do?
A solution I found is exposing the script:
app.get('/scripts', function(req, res){
return res.sendFile(path.resolve(__dirname + '/views/indexScripts.js'));
});
... then using it:
<script src="scripts"></script>
But it really seems not the correct way of handling this / prone to security breach...
Thank you
Upvotes: 0
Views: 515
Reputation: 8826
By default Express won't serve static files (JavaScript, CSS and images). You need to use the express.static
middleware to explicitly tell Express which folders it should serve from the file system.
Example:
app.use('/', express.static(path.join(__dirname, 'views')))
Then you can get your script file by navigating to http://localhost:3000/indexScripts.js
.
You can read more about the static
middleware here.
Upvotes: 1