Expressjs GET request for javascript files as text / html
I have an application mostly in Angular and I want to hook it up to Express to encrypt and send API private keys so they are not explicitly stored on the client.
My problem is the browser reads the statically served js files as text / html, which causes my javascript to not load. You can see that the response is 200 and the file is there, just isn't being interpreted correctly.
index.html has many script requests like this
<script type="text/javascript" src="/keys.js"></script>
<script type="text/javascript" src="/public/lib/underscore/underscore-min.js"></script>
<script type="text/javascript" src="/public/lib/jquery/dist/jquery.min.js"></script>
<script type="text/javascript" src="/public/lib/bootstrap/dist/js/bootstrap.min.js"></script>
...
Express Routing Code:
var express = require('express');
var path = require('path');
var app = express();
app.use(express.static(path.resolve('./public')));
app.get('*', function(req,res) {
res.sendFile(path.resolve('./public/views/index.html'));
});
app.listen(3000);
Anyone with experience with expression - what is the proper way to serve static files with different MIME types? Ultimately I need to use the text / css types as well.
source to share
You have configured your application to return index.html
for each request:
app.get('*', function(req,res) {
res.sendFile(path.resolve('./public/views/index.html'));
});
So, to be honest, it does index.html
for all and all requests, including requests that you want to return js
using tags script
. For example, asking for /public/lib/underscore/underscore-min.js
will actually return the file to /public/views/index.html
.
A simple fix would be to simply revert index.html
for the root request:
app.get('/', function(req,res) {
res.sendFile(path.resolve('./public/views/index.html'));
});
This way yours index.html
will be served in the root, but your javascript assets can still be reached because you are not using index.html
for every request.
Also, since you said that static assets can be found in /public
, there is no need to include this directory when querying them. So your script
include should look like this:
<script type="text/javascript" src="/lib/underscore/underscore-min.js"></script>
<script type="text/javascript" src="/lib/jquery/dist/jquery.min.js"></script>
<script type="text/javascript" src="/lib/bootstrap/dist/js/bootstrap.min.js"></script>
source to share