Tut06 NodeJS 1
Tut06 NodeJS 1
Tut06 NodeJS 1
Tutorial 6
To begin this tutorial, please download tut06-starter.zip from the course website.
Activity 1 instructs you how to create that project. When you finish, zip your project’s
contents (except the node_modules folder) to submit to this tutorial’s submission box.
The zip file’s name should follow this format: tclass_sid.zip where tclass is your
tutorial class name (e.g. clc01, clc02, etc.) and sid is your student’s ID (e.g.
2101040015).
1. products.json: this file contains product data that will be used as the data
source for the API.
2. dataProvider.js: this file contains getProducts function to read data from
the JSON file.
You need to create an api.js file. In the api.js file, students will use the provided
getProducts function to perform the following tasks:
Notes:
You should use a tool like Postman or curl to send HTTP requests to the server and
test the results. Download Postman here.
Example:
Activity 3 – Hello World in Node.js (Express.js)
Inside the /expressjs folder, run the command npm init to make this folder become
a Node.js project. You will need to install any non-core modules using npm.
Create the file index.js in /expressjs folder and put the following source code into it:
"use strict";
const express = require('express');
const app = express();
app.use(express.static('public'));
app.listen(8000);
Also create a folder named public inside the project folder and create a static HTML
page named hello.html inside the public folder (put any content in this HTML file).
Open a terminal in the directory with the server and enter:
node index.js
Alternatively, you can run nodemon command to start a Node project. nodemon is a tool
that restarts the server if you make changes to the JS code in order to reflect the
changes.
Access your page in the browser. Since the server is being hosted locally on your
machine, use the URL http://localhost:8000/hello (8000 is the port we specified
in index.js).
Since we told the server to serve files in the public directory, we can access a static
file at the url http://localhost:8000/hello.html.
Use Express's built-in functionality to easily extract the name parameter and
display "Hello [name]" in the response.
Activity 5 – Circles
The file /expressjs/circles.js has been created for you. Write the code of an
Express.js application in this file, then add a new GET endpoint, /math/circle/:r,
which takes a radius as a URL parameter. It should then respond in JSON with the area
and circumference.
The area of a circle is PI * r * r, and the circumference is equal to PI * 2r. You can
access PI with Math.PI.
Activity 6 – Rectangles
The file /expressjs/rectangles.js has been created for you. In this file, create a
GET endpoint, /math/rectangle/:width/:height. It should respond in JSON with
the area and perimeter based on the input width and height.