|
2 | 2 | * Exercise 3: Create an HTTP web server
|
3 | 3 | */
|
4 | 4 |
|
| 5 | +const fs = require('fs'); |
| 6 | +const url = require('url'); |
| 7 | +const path = require('path'); |
| 8 | + |
5 | 9 | const http = require('http');
|
6 | 10 |
|
7 | 11 | //create a server
|
8 | 12 | let server = http.createServer(function (req, res) {
|
9 |
| - // YOUR CODE GOES IN HERE |
10 |
| - res.write('Hello World!'); // Sends a response back to the client |
11 |
| - res.end(); // Ends the response |
| 13 | + if (req.url === '/') { |
| 14 | + fs.readFile(path.join(__dirname, 'index.html'), (err, data) => { |
| 15 | + if (err) { |
| 16 | + res.writeHead(500, { 'Content-Type': 'text/plain' }); |
| 17 | + res.end('Error loading file '); |
| 18 | + } else { |
| 19 | + res.writeHead(200, { 'Content-Type': 'text/html' }); |
| 20 | + res.end(data); |
| 21 | + } |
| 22 | + }); |
| 23 | + } else if (req.url === '/index.js') { |
| 24 | + fs.readFile(path.join(__dirname, 'index.js'), (err, data) => { |
| 25 | + if (err) { |
| 26 | + res.writeHead(500, { 'Content-Type': 'text/plain' }); |
| 27 | + res.end(' Error loading file'); |
| 28 | + } else { |
| 29 | + res.writeHead(200, { 'Content-Type': 'application/javascript' }); |
| 30 | + res.end(data); |
| 31 | + } |
| 32 | + }); |
| 33 | + } else if (req.url === '/style.css') { |
| 34 | + fs.readFile(path.join(__dirname, 'style.css'), (err, data) => { |
| 35 | + if (err) { |
| 36 | + res.writeHead(500, { 'Content-Type': 'text/plain' }); |
| 37 | + res.end('Error loading file'); |
| 38 | + } else { |
| 39 | + res.writeHead(200, { 'Content-Type': 'text/css' }); |
| 40 | + res.end(data); |
| 41 | + } |
| 42 | + }); |
| 43 | + } else { |
| 44 | + res.writeHead(404, { 'Content-Type': 'text/plain' }); |
| 45 | + res.end('Page Not Found'); |
| 46 | + } |
12 | 47 | });
|
13 | 48 |
|
14 | 49 | server.listen(3000); // The server starts to listen on port 3000
|
0 commit comments