Currently, your node.js app just knows how to serve one file, at ./view/index.html
. You need it to be able to serve different files depending on the request - for example, initially it should serve an HTML file, and then a JS file since your HTML file will have a <script>
tag referencing a JS file. While you wouldn't want the following example in a production environment, I am trying to keep it simple for the sake of example:
var fs = require('fs');
var http = require('http');
var path = require('path');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': req.url.endsWith('html') ? 'text/html' : 'application/javascript'});
fs.readFile(path.join(__dirname, req.url), function (err,data){
if (err) {
res.writeHead(404);
res.end(JSON.stringify(err));
return;
}
res.end(data);
});
}).listen(8080);
Now imagine that you have index.html
in the same directory as your Node.js script:
<!DOCTYPE html>
<html>
<head></head>
<body>
<p>Hello, world!</p>
<script src="./hello.js"></script>
</body>
</html>
As you can see, it references a JS script, hello.js
. This is going to be in the same directory as well.
// hello.js
alert('hello, world!');
Now, assuming your HTML file is named index.html
, you can access it at localhost:8080/index.html
, and it will also load your hello.js
script.