restServer.js: // http module supports to create a web server // https://nodejs.
ID: 3818404 • Letter: R
Question
restServer.js:
// http module supports to create a web server
// https://nodejs.org/api/http.html
var http = require("http");
// fs module provide functions to read and write files
// https://nodejs.org/api/fs.html
var fs = require('fs');
// url module provides utilities for URL resolution and parsing
// https://nodejs.org/api/url.html
// Used to parse query string in URI
var url = require('url')
// querystring module provides utilities for parsing and formatting URL query strings
// https://nodejs.org/api/querystring.html#querystring_querystring_parse_str_sep_eq_options
// Used to parse request body
var qs = require('querystring');
const file = "people.json";
// Function to response with error message
function returnError(code, message, response) {
response.writeHead(code, {'Content-Type': 'text/html'});
response.end(message);;
}
/*
Function to process GET request
-targetFile: file of data
-query: object parsed from query string in URL
-response: response object
*/
function doGET (targetFile, query, response) {
fs.readFile(targetFile, function(err, data) {
if (err) {
console.log(err);
returnError(404, "Internal Error.", response);
} else {
// Read data file, parse the data, and save results into a list
var dataObj = JSON.parse(data);
// If query is empty, skip the loop and return all.
// Otherwise, select targets objects based on every query condition
for (var property in query) {
// Go through all objects in the list
for (var i = 0; i < dataObj.length; i++) {
if (dataObj[i][property] != query[property]) {
// If it does NOT meet the condition
// Remove it, and
dataObj.splice(i, 1);
// Offset the index
i--;
}
}
}
if (dataObj.length == 0) {
returnError(404, "Query return no result.", response);
} else {
response.writeHead(200, {'Content-Type': 'application/json'})
// Transform the list to a string
dataObj = JSON.stringify(dataObj, null, 3);
response.end(dataObj);
}
}
});
}
/*
Function to process GET request
-targetFile: file of data
-bodyData: a new data set parsed from request body and to be saved into the target file
-response: response object
*/
function doPOST(targetFile, bodyData, response) {
// Implementation
}
/*
Function to process GET request
-targetFile: file of data
-query: object parsed from query string in URL
-response: response object
*/
function doDELETE(targetFile, query, response) {
// Implementation
}
/*
Function to process GET request
-targetFile: file of data
-bodyData: a new data set parsed from request body and to be saved into the target file
-response: response object
*/
function doPUT(targetFile, bodyData, response) {
// Implementation
}
function handleRequest(request, response) {
var reqURL = url.parse(request.url, true);
if (request.method == 'GET') {
if (reqURL.pathname == '/findUser') {
doGET(file, reqURL.query, response);
}
else {
response.writeHead(404, {'Content-Type': 'text/html'})
response.end('Invalid URI for GET');
}
} else if (request.method == 'POST') {
if (reqURL.pathname == '/addUser') {
// Require implementation
response.end('Return of POST request.');
}
else {
response.writeHead(404, {'Content-Type': 'text/html'})
response.end('Invalid URI for POST');
}
} else if (request.method == 'PUT') {
if (reqURL.pathname == '/updateUser') {
// Require implementation
response.end('Return of PUT request.');
}
else {
response.writeHead(404, {'Content-Type': 'text/html'})
response.end('Invalid URI for PUT');f
}
} else if (request.method == 'DELETE') {
if (reqURL.pathname == '/deleteUser') {
// Require implementation
response.end('Return of DELETE request.');
}
else {
response.writeHead(404, {'Content-Type': 'text/html'})
response.end('Invalid URI for DELETE');
}
} else {
response.end("Invalid REST methods.")
}
}
const PORT = 8080;
// Create and HTTP server object using the handleRequest function
var server = http.createServer(handleRequest);
// Start the server
server.listen(PORT, function() {
console.log("Server start on: http://localhost/", PORT);
})
people.json:
[
{
"id": 1,
"firstName": "Tom",
"lastName": "James",
"major": "CS",
"email": "tj"
},
{
"id": 2,
"firstName": "Jennifer",
"lastName": "Ford",
"major": "SE",
"email": "jf"
}
]
Explanation / Answer
A web server is a collection of open protocol and standards for exchangeing data among application. creating RESTful API for Library. Consider we have a JSON based database of users having the following users in a file users.json:
{
Let's implement our first RESTful API listUsers using the following code in a server.js file:
Add User
Server.js
Show Detail
Delete User.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.