-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
62 lines (51 loc) · 1.98 KB
/
server.js
File metadata and controls
62 lines (51 loc) · 1.98 KB
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
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);
var path = parsedUrl.pathname;
if(path =='/listings'){
response.writeHead(200,{'Content-Type': 'application/json'});
response.end(JSON.stringify(listingData));
}else if(path == '/'){
response.writeHead(200);
response.end();
}else{
response.writeHead(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
*/
listingData = JSON.parse(data);
//Check for errors listings = JSON.parse(data);
//Save the sate in the listingData variable already defined
//Create the server
//Start the server
server = http.createServer(requestHandler);
server.listen(port,function(){
console.log('Listening on http://127.0.0.1:8080');
});
});