const http = require('http'); const directory = [{ "name": "Brandon", "email": "brandon@mail.com" }, { "name": "Jobert", "email": "jobert@mail.com" } ] const port = 4000; const http = require('http'); // Mock Database let directory = [ { "name": "Brandon", "email": "brandon@mail.com" }, { "name": "Jobert", "email": "jobert@mail.com" } ] let port = 4000; let app = http.createServer(function(request, response){ // Route for returning all items upon receiving a GET request if(request.url == "/users" && request.method == "GET"){ // Sets the status code to 200 and sets response output to JSON data type response.writeHead(200, {'Content-Type': 'application/json'}); // using write() method of the response object to send a response to the client in a JSON format // JSON.stringify() method converts the JavaScript array of objects into JSON string. response.write(JSON.stringify(directory)); // Ends our response process response.end(); } // Route for creating a new item upon receiving a post request /* A request object contains several parts: - Headers - contains information about the request context/content - Body - contains the actual information being sent with the request */ if(request.url == "/users" && request.method == "POST"){ let requestBody = ''; // Data is received from the client and is processed in the "data" stream request.on('data', function(data){ requestBody += data; }); // request end step - only runs after the request has completely been started request.on('end', function(){ console.log(typeof requestBody); requestBody = JSON.parse(requestBody); let newUser = { "name": requestBody.name, "email": requestBody.email } directory.push(newUser); console.log(directory); response.writeHead(200, {'Content-Type': 'application/json'}); response.write(JSON.stringify(newUser)); response.end(); }); } }); app.listen(port, () => console.log(`Server running at localhost:${4000}`));