-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
41 lines (35 loc) · 1.18 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
var http = require("http");
var fs = require("fs");
var url = require("url");
var port = 8080;
/* Global variables */
var listingData;
var 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
*/
if (request.method === "GET" && parsedUrl.path === "/listings") {
response.statusCode = 200;
response.write(listingData);
} else {
response.statusCode = 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.
listingData = data;
startServer();
});
function startServer(){
server = http.createServer(requestHandler);
server.listen(port, function() {
console.log("Server listening on: http://127.0.0.1:" + port);
});
}