0

I created the simple server using nodejs and let it call html file which calls iquery. But it does not work with the browser showing the below two errors.
1. "Uncaught SyntaxError: Unexpected token <"
2. "Uncaught ReferenceError: $ is not defined at (index):13"

(Server side code)

var app = require('http').createServer(handler);
var fs = require('fs');
app.listen(1337);
function handler(req, res){
        fs.readFile('index_test1.html', function(err, data){
         if(err){
            res.writeHead(500);
            return res.end("Error");                
        }
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.write(data);
        res.end();
    });

}

(index_test1.html code)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Demo1</title>
<script src="jquery-3.3.1.min.js"></script>
<style type="text/css"></STYLE>
</HEAD>
<BODY>
  <p id="test"></p>
  <script>
    $(function(){
        $('#test').text('Hello World!');
    });
   </script>
</BODY>
</HTML>

jquery-3.3.1.min.js is in the same folder where the server.js and index_test.html exist.
I hope someone help me out on this issue. Thanks,

user_masa
  • 1
  • 1
  • ps. Life is much easier with express – Isaac Vidrine Nov 29 '18 at 21:38
  • A node.js http server serves NO files by default. So, ANY file your HTML references that is coming from your server has to have a route for it on your server. Since you have no route for the jQuery file and your code sends `index_test1.html` for every single request, when your browser asks your server to download `jquery-3.3.1.min.js`, your server sends it `index_test1.html`. Obviously, that doesn't work. I'd really recommend using Express (lightweight framework to make this a lot simpler) and then you can create a single route with `express.static()` for your static files. – jfriend00 Nov 29 '18 at 21:59

1 Answers1

1

There is one interesting thing happening with the code you have written. You are serving one file (index_test1.html) for every request right? Because you have hardcoded it in the handler.

So what is happening is when you're opening localhost:1337 you can see the index_test1.html file.

Now, in that html you import one jQuery file. But guess what, you only have ONE handler and that localhost:1337/jquery-3.3.1.min.js will go through the SAME handler and, YES! YOU GOT IT!, Serve the same exact index_test1.html file.

When you open the server in your browser open the Developer Tools and go to the Network tab. And refresh one more time to see the Network requests. You will see what I am talking about.

What you wanted to do is I guess making a Basic static file server in NodeJS (from @james' comment)? There are very good tutorials to make one out there. But I thought your problem was interesting so I explained it here. Hope this clears up some things for you.

Aritra Chakraborty
  • 12,123
  • 3
  • 26
  • 35