问题
I am using express
to serve up a page with js files using es6 modules.
About es6 modules - https://jakearchibald.com/2017/es-modules-in-browsers/
my server.js file is -
const app = express();
app.use( express.static( __dirname + '/src' ));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname + '/index.html'));
});
app.listen(8080, () => console.log('Listening on port 8080!'));
and my index.html is -
<html lang="en">
<body>
<script type="module" src="./src/test.js"></script>
</body>
</html>
In the file test.js
i am using es6 modules, thus the type="module"
in the script tag.
But test.js
script is not loading when i serve this html in browser. It is giving the error -
Failed to load module script: The server responded with a non-JavaScript MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.
I tried adding the mime type for js files in express using this in the server.js
file -
express.static.mime.define({'application/javascript': ['js']});
But still the same result. I guess i need to somehow send the mime/content-type from express for js files, but how? Please help.
回答1:
it needed a mount path. '/src'
in -
app.use( '/src', express.static( __dirname + '/src' ) );
not sure why though. will update.
回答2:
The content type should be automatically determined by the file extension.
<script type="module" src="./src/test.js"></script>
You probably want to remove /src
from the script path if you don't want to mount the static directory to /src
in your express app.
来源:https://stackoverflow.com/questions/50046558/setting-content-type-for-static-javascript-files-in-express