I installed Node.js and wanted to run a webserver that would show an html+javascript page that imports javascript functions from other .js files. Installing Node.js, running the webserver, and hosting a file locally all went very smoothly. But I keep having issues accessing the other .js files that I would like to import from test_functions.html. I have been following various online tutorials, and looking around on stack overflow, trying it in several different ways, but can't get it to work. I am thinking I might need to adjust something in the server.js file to allow my browser to acces the other files I want to import? Using .mjs extensions (instead of .js) I got my browser to recognise the functions I want to import, but it still doesn't manage to import the functions that I define in these .mjs files.
Here is the code for server.js
// use the http library to start the node server
const { read } = require('fs')
const http = require('http')
// additional library for file handling
const fs = require('fs')
// port we want to use
const port = 3000
// filename of the html page we want to show when accessing the server
const file_name = 'test_functions.html'
// create the server
const server = http.createServer(function(req, res){
// tell the brower we will be writing HTML
res.writeHead(200, {'Content-Type':'text/html'})
fs.readFile(file_name, function(error, data){
if(error){
res.writeHead(404)
read.write('Error: File ' + file_name + ' not found')
} else{
res.write(data)
}
res.end()
})
})
server.listen(port, function(error){
if (error){
console.log('Something went wrong', error)
}
else {
console.log('Server is istenng on port ' + port)
}
})
My main page, test_functions.html looks as follows
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="test.mjs" type="module">
</script>
</head>
<body>
<p>Hey, click on the button below to invoke the function</p>
<input type = "button" onclick = "showAlert()" value = "Click Me">
</body>
</html>
while the function that I placed in test.mjs looks as follows
export default function showAlert()
{
alert("welcome");
}
console.log('hello')
After trying it in various ways, the browser keeps giving me the following two errors:
- Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "text/html". Strict MIME type checking is enforced for module scripts per HTML spec.
- Uncaught ReferenceError: showAlert is not defined at HTMLInputElement.onclick