- Engineering
- Computer Science
- your objective is to create a server that provides listing...
Question: your objective is to create a server that provides listing...
Question details
Your objective is to create a server that provides listing data from a JSON file. To accomplish this, you will:
- use the File System module to load listings.json into memory
- create a request handler with the URL module to send the listing data on a GET request to localhost:8080/listings
- use the HTTP module to create a server that makes use of this request handler
We have provided skeleton code that will help guide you in completing this assignment. There is also a file named server.tests.js containing unit tests to test your server once completed.
I have this so far, but it doesn't work:
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);
if (request.method === "GET" && parsedUrl.pathname === "/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) {
listingData = data;
startServer();
});
function startServer(){
server = http.createServer(requestHandler);
server.listen(port, function() {
console.log("Server listening on: http://127.0.0.1:" + port);
});
}
Solution by an expert tutor
