I get the following error message when I try to run a local node server with a very simple application (see coding below).
Loading module from “http://localhost:
Essentially you have a server that for any given request, serves the content of your index.html
file - regardless of what that request might look like. A browser therefore receives the HTML and begins to interpret it making another request for the src
of your script
tag and since the server only serves your index.html
file, the browser receives your HTML file a second time when it expected javascript.
Typically you'd create a server first then construct responses based on the request as input. A primitive example of serving your static files how you intended might look like the following:
const http = require('http')
const fs = require('fs')
const PORT = 8080
http
.createServer((request, response) => {
fs.readFile(`.${request.url}`, (err, data) => {
if (err) {
response.writeHeader(404, {
'Content-Type': 'text/plain'
})
response.write('404 Not Found')
response.end()
return
}
if (request.url.endsWith('.html')) {
response.writeHeader(200, {
'Content-Type': 'text/html'
})
}
if (request.url.endsWith('.js')) {
response.writeHeader(200, {
'Content-Type': 'application/javascript'
})
}
response.write(data)
response.end()
})
})
.listen(PORT)
Do note that this example is too trusting of the client and you would normally want to sanitise the request in some way. I kept to vanilla javascript but once you're comfortable with how it works, it's worth checking out Express as it will simplify the routing / mime-type boilerplate etc.