forked from Arun2642/ExtraCreditGameWebserver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmyFirstHTTPServer.js
52 lines (43 loc) · 1.48 KB
/
myFirstHTTPServer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
//Lets require/import the HTTP module
var http = require('http');
//Added to require the httpdispatcher module
var dispatcher = require('./httpdispatcher');
//Lets define a port we want to listen to
const PORT=8080;
//For all your static (js/css/images/etc.) set the directory name (relative path).
dispatcher.setStatic('resources');
dispatcher.setStaticDirname('.');
//A sample GET request
dispatcher.onGet("/page1", function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Page One');
});
//Another sample GET request
dispatcher.onGet("/page1/testpath", function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Page One');
});
//A sample POST request
dispatcher.onPost("/post1", function(req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Got Post Data');
});
//We need a function which handles requests and send response
//Lets use our dispatcher (Updated version of this function now below)
function handleRequest(request, response){
try {
//log the request on console
console.log(request.url);
//Disptach
dispatcher.dispatch(request, response);
} catch(err) {
console.log(err);
}
}
//Create a server
var server = http.createServer(handleRequest);
//Lets start our server
server.listen(PORT, function(){
//Callback triggered when server is successfully listening. Hurray!
console.log("Server listening on: http://localhost:%s", PORT);
});