0

I'm developing a simple server that loads an HTML page after a request.

The code works fine, but i'm not able to load the local resources "connected" to my HTML page (CSS and Javascript files), i get the error mentioned in the title.

This is my Node.js server:

var server = http.createServer(function(request, response){
var path = url.parse(request.url).pathname;
console.log("Print path:"+ path);

switch(path){
    case '/':
        response.writeHead(200, {'Content-Type': 'text/html'});
        response.write('hello world');
        response.end();
        break;
    case '/index.html':
        console.log("print full address:"+__dirname + path);
        fs.readFile(__dirname + path, function(error, data){
            if (error){
                response.writeHead(404);
                response.write("opps this doesn't exist - 404");
                response.end();
            }
            else{
                response.writeHead(200, {"Content-Type": "text/html"});
                response.write(data, "utf8");
                response.end();
            }
        });
        break;
    default:
        response.writeHead(404);
        response.write("opps this doesn't exist - 404");
        response.end();
        break;
}
});

server.listen(5000);

The index.html file is loaded, but i won't be able to access to all the local scripts and stylesheets inside my HTML file.

This is my HTML (short version, just the script and stylesheet part):

<!DOCTYPE html>
<html lang="en" >
<head>
    <meta charset="UTF-8">
    <title>A Pen by  Mattia Surricchio</title>
    <link rel='stylesheet' href='02cbe09766a509e291eb2a444.css'>
    <link rel='stylesheet' href='http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css'>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <script src='02cbe09766a509e291eb2a444.js'></script>
    <script src='http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js'></script>
    <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
    <script src='https://cdnjs.cloudflare.com/ajax/libs/tone/13.8.9/Tone.min.js'></script>
    <script  src="script.js"></script>

</body>

All the files are in the same folder of my node.js file, so the server, HTML, CSS and Javascript files are all in the same folder.

I'm accessing the server with http://localhost:5000/index.html in my browser.

I checked the paths with console.log() and they seem correct (the HTML is loaded properly, the problem are the CSS and Javascript files inside the page).

What could be the problem?

PS: If i load the index.html page by itself (just opening it with the browser), all the files are loaded and showed correctly.

EDIT: I partially solved the problem moving to express.js, here's my new server (i followes this answer:nodejs/express include local js file):

var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var  path = require('path');
var express = require('express');


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

app.get('/', function(req, res) {
    res.redirect('index.html');
});

My directory structure is the following:

root/
  app.js //this is my node.js server
  node-modules
  package.json
  Pad/
      index.html
      script.js
      style.css

With this solution i'm able to load the HTML file, including the script.js file and the style.css that are linked inside the HTML file.

However, i'm also using local modules (in this particular case i'm using Tone.js and Tonal.js) which have been installed using npm inside the folder node-modules.

How do i access those resources? I'm getting error 404.

Do i have to move those resources inside my Pad folder?

Mattia Surricchio
  • 1,362
  • 2
  • 21
  • 49

2 Answers2

0

You need to define a route for your CSS file(s) as you do it for index.html

case '/style.css':
    res.writeHead(200, {'Content-Type': 'text/css'});
    res.write(fs.readFileSync(__dirname + path, 'utf8'));
    res.end();
    break;

Lameaux
  • 11
  • 1
  • How do i do it? I just add that case to my switch and then it will load all the CSS included in my HTML? – Mattia Surricchio Aug 24 '19 at 12:55
  • @MattiaSurricchio Yes. In real-life apps though you would use a static server module or configure a separate static server such as Apache, Nginx or IIS (or even AWS S3 or Akamai or Couldflare or Google Cloud CDN etc.) – slebetman Aug 24 '19 at 21:45
  • So basically I should move to express.js and set a static folder containing all my resources? Css, Javascript ecc... I was curious if it was feasible this way. I'll implement the solution using express and then I'll answer to my own question – Mattia Surricchio Aug 24 '19 at 21:49
  • Anyway, I tried to add just another case switch, but it doesn't work. I think that each switch is triggered by the url written in the browser. If I write .../index.html it won't load the css, since it hasn't been asked and it won't trigger the switch, am I right? – Mattia Surricchio Aug 24 '19 at 21:53
0

You need to call those files seperately like you call html file in the first place. Create direct url list for files that you want to parse first, then make get requests for them seperately.

Zubeyir
  • 11
  • 6