In: Computer Science
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:
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.
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