jctxt
jctxt

Reputation: 23

How do I correctly include a script on a locally hosted node server?

I stripped down the problem to the bare minimum, here's the situation:

The most basic index.html possible, with no DOM elements and only one script, located in the same folder:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
    </head>
    <body>
        <script src="script.js"></script>
    </body>
</html>

The simplest possible script.js, which is just a console.log statement:

console.log("%cI'm working!", "font: bold 17px arial; color: #3e9;");

a very simple server.js:

var http = require('http');
var fs = require('fs');
var index = fs.readFileSync('index.html');

const PORT = 3000;

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.end(index);
}).listen(PORT);

console.log(`Listening on port ${PORT}`);

If I run the page locally, i.e. by launching index.html with my web browser, everything works fine, and I see the log in the console. If, instead, I try to launch the server using node server.js, I come across a very weird error in which script.js appears to contain the contents of index.html, resulting in a syntax error.

Here's a screenshot of DevTools for clarity: Screenshot of DevTools

What causes this? How can I correctly include the script on my local server?

Upvotes: 1

Views: 353

Answers (1)

user15388024
user15388024

Reputation:

Your server responses all requests with index.html. You need a routing.

The most basic approach is

var http = require('http');
var fs = require('fs');
var index = fs.readFileSync('index.html');
var script = fs.readFileSync('script.js');

const PORT = 3000;

http.createServer(function (req, res) {
  if (req.path.endsWith('script.js')) {
    res.writeHead(200, {'Content-Type': 'text/javascript'});
    res.end(script);
  } else {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end(index);
  }
}).listen(PORT);

console.log(`Listening on port ${PORT}`);

This should be only the first step to understand the basics. Usually you would use a framework like Express with a routing as described in https://expressjs.com/en/guide/routing.html and serve static files as described in https://expressjs.com/en/starter/static-files.html

An example with Express:

const express = require('express');
const app = express();
const port = 3000;

app.use(express.static(__dirname));

But this will serve all files in your project root. You should restructure your project and move the files for your website into a separate folder, e.g. public:

const express = require('express');
const app = express();
const port = 3000;

app.use(express.static(path.join(__dirname, 'public')));

Upvotes: 1

Related Questions