-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathServer.js
95 lines (72 loc) · 3.4 KB
/
Server.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
const http = require('http');
const fs = require('fs');
const port = 6889;//port for the server
async function notfoundpage(response, url) {//404 page goes here
//response.writeHead(404);
response.write('404 page not , code: ', url);
console.error('File not found: ', url)
}
const server = http.createServer(function (request, response) {///Create server
console.log('requested Url: ', request.url);
response.setHeader('Acess-Control-Allow-Origin', '*');//allow access control from client, this will automatically handle most media files
switch (request.url) {
case '/': case '/index.html':
try {
response.writeHead(200, { 'Content-type': 'text/html' });//200 ok
fs.readFile('./www/index.html', function (err, databuffer) {
if (err) {
notfoundpage(response, 'index');
} else {
response.write(databuffer);
}
response.end();//end response
})
} catch (err) {
console.log('Catastrophy on index: ', err)
}
break;
case '/get/test'://A test get
try {
console.log('test get from server');
response.writeHead(200, { 'Content-type': 'application/json' });
response.end(JSON.stringify({ test: 'Server is okay' }))
} catch (error) {
console.log('Catastrophy on test get: ', err)
}
break;
case '/post/test'://A test post
console.log('test post to server');
request.on('data', function (data) {
console.log('Posted: ', JSON.parse(data))
response.end()
});
break;
default://
//These need to be handled manually
if (request.url.indexOf('.css') != -1) {//requestuested url is a css file
response.setHeader('Content-type', 'text/css');//Set the header to css, so the client will expects a css document
} else if (request.url.indexOf('.js') != -1) { //requestuested url is a js file
response.setHeader('Content-type', 'application/javascript');//Set the header to javascript, so the client will expects a javascript document
} else if (request.url.indexOf('.html') != -1) {//requestuested url is a html file
response.setHeader('Content-type', 'text/html');//Set the header to html, so the client will expects a html document
} else {
//media handled automatically
}
fs.readFile(request.url.replace('/', 'www/'), function (err, data) {//read request.url.replace('/', '') file
if (err) {//error because file not found/inaccesible
notfoundpage(response, request.url);//show 404 page
} else {
response.writeHead(200);//200 ok
response.write(data);//responsepond with data from file
}
response.end();//end responseponse
})
}
})
server.listen(port, function (err) {//Listen to a port with server
if (err) {
console.error(err);
} else {
console.log('Listening on port: ', port);
}
})