Question

In: Computer Science

Given a server.js file that uses express (i.e. var app = express();), write code to respond...

Given a server.js file that uses express (i.e. var app = express();), write code to respond to the routes below as specified in the description.  NOTE: all callback functions must be written in the new ES6 "Arrow Function" syntax:

(1) Match the "GET" route "/users" and accept query string of "page=2&perPage=10" in the url, i.e. "/users? page=2&perPage=10". This route must show the following in browser:

Query String Parameters:

  • Page: 2
  • perPage: 10

Note: the query string parameters may have different values, e.g. page=5&perPage=15. [3 Marks]

(2) Match the "GET" route "/user/userID" and return a JSON formatted string: {message: userID} where userID is the value, e.g. 022066172, passed in the url.  [2.5 Marks]

(3) Instead of defining a route, setup the folder named "public" on express server to serve static files. [2 Marks]

(4) Match the "route" that is invoked if no other paths are matched (you may assume that it is located below the other route definitions). Ensure that a 404 status code and the plain text message: "Resource is not found!" are send back.

Solutions

Expert Solution

Express is a node js web framework which is really easy to understand and efficient to use. In our given problem we are required to create two paths and for every other path send a 404 Error

Also we are required to define the callback functions in ES6 syntax which is arrow functions.

To solve the given prroblem we will start in our code by importing express package and create a new app with the express constructor.

We will define three routes in total, one for /users, one for /user/userid and one for default which is hit when the request does not match any other paths

const express = require("express");
const app = express()
const port = 3000

// setting up the folder named "public" on express server to serve static files
// the folder public is in the same level as this file
app.use(express.static('public'));

// route to match queries like /users?page=1&pageId=3231
app.get('/users', (req, res) => {
    // request send in query parameters are available in req.query object
    res.send(`Query String Parameters:<br/>Page: ${req.query.page}<br/>perPage: ${req.query.perPage}`);
})

// route to match queries like /user/434242
app.get('/user/:userid', (req, res) => {
    // req.params object holds the request value
    res.json({message: req.params.userid})
})

// any request which doesn't match above two routes is handled here
app.get('/*', (req, res) => {
    // we set the http error code and message
    res.status(404).send('Resource is not found!')
})

// we make the express app at port defined 
app.listen(port, () => {
  console.log(`App listening at http://localhost:${port}`)
})

SCREENSHOT OF CODE AND SAMPLE OUTPUT

ACCESSING STATIC FILE SERVED BY OUR EXPRESS APP. SEE ABOVE SCREENSHOT FOR THE FOLDER STRUCTURE AND FILE CONTENT


Related Solutions

JavaScript 1. FizzBuzz Submit js file with functioning code Write a program that uses console.log to...
JavaScript 1. FizzBuzz Submit js file with functioning code Write a program that uses console.log to print all the numbers from 1 to 120, with two exceptions. For numbers divisible by 4, print "Fizz" instead of the number, and for numbers divisible by 10 (and not 4), print "Buzz" instead. When you have that working, modify your program to print "FizzBuzz", for numbers that are divisible by both 4 and 10 (and still print "Fizz" or "Buzz" for numbers divisible...
// 5. Predict what the following code will print (write it down), then try it. var...
// 5. Predict what the following code will print (write it down), then try it. var myVariable = "global"; var myOtherVariable = "global"; function myFunction() { var myVariable = "local"; return myVariable; } function myOtherFunction() { myOtherVariable = "local"; return myOtherVariable; javascript
Given the StudentIDDriver.java file, fill in the ‘gaps’ in the code (designated by insert code here...
Given the StudentIDDriver.java file, fill in the ‘gaps’ in the code (designated by insert code here that “exercises” (tests) the StudentID class by calling its methods. There are six occurrences of ‘insert code here comments’. Above these are comments that help you understand what your code should accomplish.   Don’t forget to comment your StudentIDDriver.java file (including a prologue section at the top of the file). Create a project in Eclipse for your StudentIdDriver. Add another class for it StudentId Sample...
The code file is attached. Portion of the code is given (1, 2, 3, 4). You...
The code file is attached. Portion of the code is given (1, 2, 3, 4). You have to write the code for the remaining items (5, 6, 7). #include <iostream> using namespace std; struct node { int data; node* next; }; node* head=NULL; void appendNode(int value) { node *newNode, *curr; newNode = new node(); newNode->data=value; newNode->next=NULL; if (!head) head=newNode; else { curr=head; while (curr->next) curr = curr->next; curr->next = newNode; } } void insertNode(int value) { node *newNode, *curr, *previous;...
Using the code below from “LStack.h” file, write the code for a main program that takes...
Using the code below from “LStack.h” file, write the code for a main program that takes as input an arithmetic expression. The program outputs whether the expression contains matching grouping symbols. For example, the arithmetic expressions { 25 + ( 3 – 6 ) * 8 } and 7 + 8 * 2 contains matching grouping symbols. However, the expression 5 + { ( 13 + 7 ) / 8 - 2 * 9 does not contain matching grouping symbols....
modify code to write the output as an HTML table to a file in the output...
modify code to write the output as an HTML table to a file in the output directory. The file that is saying to work at : SOURCE CODE IN PERL: print "Enter principal amount: "; $P=; while($P<=0) { print "Principal must be positive. Try again: "; $P=; } print "Enter number of times interest is applied in a year: "; $n=; while($n!=12 && $n!=4 && $n!=2 && $n!=1) { print "It must be 12, 4, 2 or 1. Try again:...
Ubuntu Linux HW5: text processing; scripting 1. Write a Linux command to rewrite the /var/passwd file...
Ubuntu Linux HW5: text processing; scripting 1. Write a Linux command to rewrite the /var/passwd file to have a tab for each delimiter ':'. Hint: use tr 2. Write a Linux command to extract the user names and sort them. Hint: use cut 3. Write a for loop to to display a time table, e.g., 17 x 1 = 17; 17 x 2 = 34; etc., as follows: 17 x 1 = 17 17 x 2 = 34 17 x...
a – DSB. Write the code for an m-file (script) to generate a DSB signal. The...
a – DSB. Write the code for an m-file (script) to generate a DSB signal. The modulating (message) signal is a single tone signal with frequency 1kHz and the carrier frequency is 30kHz. Time Vector: 3001 points over range from 0 to 3ms (3 cycles of the modulating signal). Plot your original message signal both in time and its spectrum. (Note: the Matlab examples 6.1 and 6.2 will help, but use the cosine functions for your signals instead of sine...
I didn't know , how to write this code // This file is part of www.nand2tetris.org...
I didn't know , how to write this code // This file is part of www.nand2tetris.org // and the book "The Elements of Computing Systems" // by Nisan and Schocken, MIT Press. // File name: projects/04/Fill.asm // Runs an infinite loop that listens to the keyboard input. // When a key is pressed (any key), the program blackens the screen, // i.e. writes "black" in every pixel; // the screen should remain fully black as long as the key is...
write a program in c++ that opens a file, that will be given to you and...
write a program in c++ that opens a file, that will be given to you and you will read each record. Each record is for an employee and contains First name, Last Name hours worked and hourly wage. Example; John Smith 40.3 13.78 the 40.3 is the hours worked. the 13.78 is the hourly rate. Details: the name of the file is EmployeeNameTime.txt Calculate the gross pay. If over 40 hours in the week then give them time and a...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT