I am very new to node.js. I am trying to write to the response an html file named index.html which has a reference to a javascript file test.js:
<!-- Content of index.html -->
<html>
<head>
<script src="test.js"></script>
</head>
<body>
<h2>Hello</h2>
</body>
</html>
There is only one line in my test.js
console.log("asdf")
Now, to use node.js to display index.html, I wrote the following main.js
let http = require("http")
let fs = require("fs")
let hostname = "127.0.0.1"
let port = 3000
let server = http.createServer((request, response) => {
fs.readFile("./index.html", (error, html) => {
response.statusCode = 200;
response.setHeader("Content-Type", "text/html")
response.write(html)
response.end()
})
})
I entered node main.js in the terminal, and typed http://127.0.0.1:3000/ in the browser. The console shows an exception saying
Uncaught SyntaxError: Unexpected token
<
It turns out that the browser got test.js wrong. As shown in the image below, it seems that the browser thinks text.js contains the content of index.html.
What went wrong?
All files mentioned are organized in the following manner:
.
├── index.html
├── main.js
└── test.js

test.js? You cannot have plainHTMLtags in there.test.js,console.log("asdf"), @ishmaelMakitlaDOCTYPEdeclaration, and escaping/at closing</script>when returning response text?