I am creating a single and a very simplest form of webpages where, i have created a js file for Nodejs: which looks like this:-
var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
fs.readFile('treeDemoinJavaScript.html', function (err, html) {
if (err) {
throw err;
}
res.writeHeader(200, {'Content-Type': 'text/html'});
res.write(html);
res.end();
});
}).listen(8090);
Then comes the file treeDemoinJavaScript.html, which looks like this:-
<!DOCTYPE html>
<html>
<body>
<br>
<h2>Linked List in Javascript</h2>
<p>Click the button to sort the array in ascending order.</p>
INPUT
<input type="text" id="inputList"> </input>
<button onclick="insertInTree()">Add in Tree</button>
</br>
<button onclick="insertIntoTree()" id="show">Show in Tree</button></br></br>
<button onclick="search()" id="search">Search in Tree</button>
<input type="text" id="searchtextbox" visibility="hidden" placeholder="type the input "> </input>
<button onclick="deletefunction()" id="delete">Delete from Tree</button>
<p id="demo">welcome, the array is as follows: </p>
<p id="demo2">welcome, the array is as follows: </p>
<script type="text/javascript" src="treeDemoInJavaScript.js">
</script>
</body>
</html>
Now what the problem is that even if i place a simple alert function in my treeDemoInJavaScript.js file that doesn't work and when i run
by doing
$terminal- node startNodeDemo.js
Then in the chrome i get the following error, like this:
Error shows :- Unexpected token <
and i don't get that why does browser running the treeDemoInJavaScript.js file and showing error in it.
fs, and not something like express?treeDemoinJavaScript.htmlno matter what is requested of it. So, the browser requeststreeDemoinJavaScript.htmland the server sends that. Then the browser parses that HTML file and finds a reference totreeDemoinJavaScript.jsso it request that from the web server, but your web server just sends ittreeDemoinJavaScript.htmlwhich is why you get an error when the browser tries to run that as Javascript. You need to support a route in your web server for/treeDemoinJavaScript.js.