1

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.

enter image description here

What went wrong?

All files mentioned are organized in the following manner:

.
├── index.html
├── main.js
└── test.js
4
  • Can you show the content of test.js? You cannot have plain HTML tags in there. Commented Dec 24, 2016 at 21:08
  • As I said, there is only one line in test.js, console.log("asdf"), @ishmaelMakitla Commented Dec 24, 2016 at 21:09
  • Have you tried including DOCTYPE declaration, and escaping / at closing </script> when returning response text? Commented Dec 24, 2016 at 21:21
  • try adding a doctype declaration and see if that helps. Commented Dec 24, 2016 at 21:23

1 Answer 1

3

Your server is sending the contents of index.html no matter what the browser is asking for. Below is a verbose example of how you may want to handle requests for index.html vs test.js.

let server = http.createServer((request, response) => {
  if(request.url === '/' || request.url === '/index.html') {
    fs.readFile("./index.html", (error, html) => {
      response.end(html);
    });
  } else if(request.url === '/test.js') {
    fs.readFile("./test.js", (error, js) => {
      response.end(js);
    });
  } else {
    response.end('idk what to send u, sowie');
  }
});

As you can see, some of the code repeats! You can refactor the code to say "please try to give them the exact file they're asking for; if I hit an error when reading the file, it must not exist, therefore I will send them a 404 response."

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.