I'm trying to run my site on localhost with Node.js. It downloads, but the script specified in my index file does not work. Looking at the page sources it seems that my script file has turned into an exact copy of my index file. What could cause that?
Here's my code:
const http = require('http')
const fs = require('fs')
const port = 3000
const server = http.createServer(function(req, res) {
res.writeHead(200, { 'Content-Type': 'text/html'})
fs.readFile('index.html', function(error, data) {
if (error) {
res.writeHead(404)
res.write('Error: File 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 listening on port ' + port)
}
})
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<h1>Hi</h1>
<div id="words">*</div>
<script src="script.js"></script>
</body>
</html>
script.js
words.innerHTML += "1";
You don't have any logic to return different responses (e.g. based on the requested URL), so your server always responds with the index.html document, even when other resources are requested (like your script).
You can implement the logic yourself, or you can use existing software to do it. A very commonly used one is called express.