-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
66 lines (50 loc) · 1.82 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
var http = require('http'),
fs = require('fs'),
url = require('url'),
port = 8080;
/* Global variables */
var listingData, server;
var requestHandler = function(request, response) {
var parsedUrl = url.parse(request.url);
switch(parsedUrl.pathname.toLowerCase()){
case "/listings":
if (request.method === 'GET') {
response.write(listingData);
break;
}
default:
response.statusCode = 404;
response.write("Bad gateway error");
}
response.end();
/*
Your request handler should send listingData in the JSON format as a response if a GET request
is sent to the '/listings' path. Otherwise, it should send a 404 error.
HINT: Explore the request object and its properties
HINT: Explore the response object and its properties
https://code.tutsplus.com/tutorials/http-the-protocol-every-web-developer-must-know-part-1--net-31177
http://stackoverflow.com/questions/17251553/nodejs-request-object-documentation
HINT: Explore how callback's work
http://www.theprojectspot.com/tutorial-post/nodejs-for-beginners-callbacks/4
HINT: Explore the list of MIME Types
https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Complete_list_of_MIME_types
*/
};
fs.readFile('listings.json', 'utf8', function(err, data) {
/*
This callback function should save the data in the listingData variable,
then start the server.
HINT: Check out this resource on fs.readFile
//https://nodejs.org/api/fs.html#fs_fs_readfile_path_options_callback
HINT: Read up on JSON parsing Node.js
*/
//Check for errors
if (err) throw err;
//Save the sate in the listingData variable already defined
listingData = data;
//Creates the server
server = http.createServer(requestHandler);
server.listen(port, function() {
console.log("server listening on: http://localhost:8080");
});
});