forked from CEN3031-spr16/UF-Directory-App-Assignment
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
50 lines (39 loc) · 1.33 KB
/
server.js
File metadata and controls
50 lines (39 loc) · 1.33 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
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);
/*
Your request handler should send listingData in the JSON format 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
http://stackoverflow.com/questions/17251553/nodejs-request-object-documentation
*/
// GET request is sent to the 'listings' path.
// Sent status code 200.
if (parsedUrl.pathname === "/listings" ){
response.writeHead(200,{'Content-Type' :'application/json'});
response.write(listingData);
response.end();
}
// Sent status code 404.
else{
response.writeHead(404);
response.write('Bad gateway error');
response.end();
}
};
fs.readFile('listings.json', 'utf8', function(err, data) {
/*
This callback function should save the data in the listingData variable,
then start the server.
*/
// Data is saved in a string buffer from the JSON object.
listingData = JSON.stringify(JSON.parse(data));
// Server gets created and start listening on the port.
server = http.createServer(requestHandler);
server.listen(port);
});