Serve multiple type files on pure node.js

I have a simple pure node.js server which sends back html page on request. In my html page i have connected js file. When i make a request i get on response the html page but no the js file. In my console i got an error.

Uncaught SyntaxError: Unexpected token '<'

my node.js server file:

const http = require('http');
const fs = require('fs');
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html', });
    fs.readFile('index.html', function(err, data){
        if(err){
          return console.log(err);
        }
      res.end(data);
    });
}).listen(8080);
console.log('Server is running on Port: 8080');

my html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>here</h1>
    <script src="./app.js"></script>
</body>
</html>

Any suggestions how to send multiple files on request with pure js ?

Upvotes: 1

Views: 271

Answers (1)

eol
eol

Reputation: 24565

You're currently serving all requests with index.html, so when the browser requests app.js you do not get the script, but the index-page instead, hence the error.

You'd need to check the request path in your server's callback and then send the correct file (see this for a more detailed example):

http.createServer(function (req, res) {
    if (req.path === '/app.js') {
       // read app.js file and send it to the client
    } else {
      res.writeHead(200, {'Content-Type': 'text/html', });
      fs.readFile('index.html', function(err, data){
        if(err){
          return console.log(err);
        }
       res.end(data);
    });
}).listen(8080);

You see that this is pretty cumbersome, so I highly recommend using a framework like express (it provides a middleware to serve static files out of the box) to do this.

Upvotes: 2

Related Questions