Implementing HTTP Servers

Hello, if you have any need, please feel free to consult us, this is my wechat: wx91due

Implementing HTTP Servers and RESTful APIs with Node.js

1 Introduction

During the 90s, the adoption of the World Wide Web grew exponentially. A variety of commercial ventures explored numerous use cases, revolutionizing interactions between companies, their customers, and other businesses. The figure on the right illustrates several integration points between businesses, often referred to asbusiness-to-business (B2B) interactions. Interactions between businesses and customers are commonly known asbusiness-to-consumer (B2C) interactions. Many companies have largely automated customer interactions by implementing online storefronts where customers can browse products, place orders, submit reviews, and even process returns.

Creating visually appealinguser interfaces is essential to capture customer attention, encourage purchases through marketing ads, and build long-term relationships through incentives like discounts and loyalty programs. User interfaces, as the name suggests, focus on application aspects that interact with users through visually engaging representations of data. Up to this point, these interfaces have used hard-coded JSON files, such ascourses.json andmodules.json, to render data. Interfaces have been built to render and manipulate this data, updating the screen to reflect changes.

However, these updates have not been permanent; refreshing the browser results in lost changes and a reset application state. JavaScript applications running on clients like browsers, game consoles, or TV boxes have limited options for retrieving and storing data permanently. The next chapters address the challenges of retrieving, storing, updating, and deleting data permanently on remote servers and databases from React.js applications.

2 Installing and configuring an HTTP Web server

The Kanbas React Web application built so far is theclient in aclient/server architecture. Users interact with client applications that implement user interfaces relying on servers to store data and execute complex logic that would be impractical on the client. Clients and servers interact through a sequence of requests and responses. Clients sendrequests to servers, servers execute some logic, fulfill the request, and thenrespond back to the client with results. This section discusses implementing HTTP servers using Node.js.

2.1 Introduction to Node.js

JavaScript is generally recognized as a programming language designed to execute in browsers, but it has been rescued from its browser confines by Node.js. Node.js is a JavaScript runtime to interpret and execute applications written in JavaScript outside of browsers, such as from a desktop console or terminal. This allows JavaScript applications written for the desktop to overcome many limitations faced by those in the browser. JavaScript running in a browser is restricted, with no access to the filesystem or databases, and limited network capabilities. In contrast, JavaScript running on a desktop has full access to the filesystem, databases, and unrestricted network access. Conversely, desktop JavaScript applications generally lack a user interface and offer limited user interaction, while browser-based JavaScript applications provide rich and sophisticated interfaces for user interaction.

2.2 Installing Node.js

Node.js is a JavaScript runtime that can execute JavaScript on a desktop, allowing JavaScript programs to breakout from the confines and limitations of a browser. Node.js was installed during previous assignments while implementing the React.js Web application. Confirm the installation and check the version by typing the following in your computer terminal or console application.

$ node  -v

v22.11.0

If a Node installation is present, its version will be displayed on the console; otherwise, an error message will be shown, indicating that Node.js needs to be downloaded and installed from the URL below. As of this writing, Node.js 22.11.0 was the latest version, but any version recommended on Node's website can be installed.

https://nodejs.org/en

Once downloaded, double click on the downloaded file to execute the installer, give the operating system all the permissions it requests, accept all the defaults, let the installer complete, and restart the computer. Once the computer is up and running again, confirm Node.js installed properly by running the commandnode -v  again from the command line.

2.3 Creating a Node.js project

Another tool installed along with Node.js isnpm orNode Package Manager. We've been usingnpmto run React applications in previous assignments. Thenpm command can be used to accomplish many more tasks, but like the name suggests, its main purpose is to install packages or executable code thatnpm can download and install in the local computer. Another important purpose ofnpm is to create brand new Node.js projects. To create a Node.js project create a directory with the name of the desired project and then change into that directory as shown below. Choose a directory name that does not contain any spaces, is all lowercase, and uses dashes between words.

Another tool that is installed along with Node.js isnpm, orNode Package Manager.Npm has been used to run React applications in previous assignments. Many more tasks can be accomplished using the npm command, but as the name suggests, its main purpose is to install packages or executable code that can be downloaded and installed on the local computer. Another important purpose of npm is the creation of brand new Node.js projects. To create a Node.js project, a create directory with the name of the desired project, and then navigate into that directory, as shown below. Choose a directory name that does not contain any spaces, is all lowercase, and uses dashes between words.

$ mkdir  kanbas-node-server-app

$ cd     kanbas-node-server-app

Once in the directory, usenpm initto create a new Node.js project as shown below. This will kickoff an interactive session asking details about the project such as the name of the project and the author. The following is a sample interaction with sample answers. Each question provides a default answer which can be accepted or skipped by just pressing enter. It is fine to initially keep all the default values since they can be configured at a later time.

$ npm  init

package name: (kanbas-node-server-app)

version: (1.0.0)

description: Node.js HTTP Web server for the Kanbas application

entry point: (index.js)

test command:

git repository: https://github.com/jannunzi/kanbas-node-server-app

keywords: Node, REST, Server, HTTP, Web Development, CS5610, CS4550

author: Jose Annunziato

license: (ISC)

The configuration will be written into a new file calledpackage.json in the JSON format and it's distinctive of Node.js projects, likepom.xml files might be distinctive for Java projects.

2.4 Creating a Simple Hello World Node.js program

Open the project created earlier with an IDE such as Visual Studio Code or IntelliJ, and at the root of the project, create a JavaScript file calledHello.js with the content shown below. The script uses theconsole.log() function to print the string'Hello World!' to the console and it is a common first program to write when learning a new language or infrastructure.

Hello.js

 

console.log("Hello World!");

 

At the command line, run theHello.js application by using thenodecommand and confirm the application printsHello World! to the console as shown below.

$ node  Hello.js

Hello World!

Node.js programs consist of JavaScript files that are executed with thenode command line interpreter. The following sections describe writing JavaScript applications that implementHTTP Web servers andRESTful Web APIs to integrate with React.js user interfaces. Upcoming assignments describe writing JavaScript applications that store and retrieve data from databases such asMongoDB.

2.5 Creating a Node.js HTTP Web server

Express is one of the most popular Node.js libraries that simplify creating HTTP servers. Express will be used to implement HTTP servers that can respond to HTTP requests from any HTTP client such as the React.js client implemented in earlier assignments. From the root directory of the Node.js project, install theexpress library from the terminal as shown below.

$ npm  install  express

Confirm that anexpress entry appears inpackage.json in thedependencies property. It is important these dependencies are listed inpackage.json so that they can be re-installed by other colleagues or when deploying to remote servers and cloud platforms such asAWS,Heroku, orRender.js. New libraries are installed in a new folder callednode_modules. More Node.js packages can be found at npmjs.com. The followingindex.js implements an HTTP server that respondsHello World! when the server receives an HTTP request at the URL http://localhost:4000/hello. Copy and paste the URL in a browser to send the HTTP request and the browser will render the response from the server. Therequire function is equivalent to theimport keyword and loads a library into the local source. Theexpress() function call creates an instance of the express library and assigns it to local constantapp. Theapp instance is used to configure the server on what to do when various types of requests are received. For instance the example below uses theapp.get() function to configure anHTTP GET Request handler by mapping the URL pattern'/hello' to a function that handles the HTTP request.

index.js

 

constexpress=require('express')

constapp=express()

app.get('/hello', (req, res) => {res.send('Hello World!')})

app.listen(4000)

// equivalent to import

// create new express instance

// create a route that responds 'hello'

// listen to http://localhost:4000

A request to URL http://localhost:4000/hello triggers the function implemented in the second argument ofapp.get(). The handler function receives parametersreq andres which allows the function to participate in therequest/response interaction, common inclient/server applications. Theres.send() function responds to the request with the textHello World! Usenode to run the server from the root of the project as shown below.

$ node  index.js

The application will run, start the server, and wait at port4000 for incoming HTTP requests. Point your browser tohttp://localhost:4000/hello and confirm the server responds withHello World! Stop the server by pressingCtrl+C. The stringhttp://localhost:4000/hello is referred to as aURL (Uniform Resource Locator) and is used to .

2.6 Configuring Nodemon

React Web applications automatically transpile and restart every time code changes. Node.js can be configured to behave the same way by installing a tool called  nodemon  which monitors file changes and automatically restarts the Node application. Install nodemon globally (-g) as follows.

$ npm  install  nodemon  -g

OnmacOS you might need to run the command as asuper user as follows. Type your password when prompted.

$ sudo  npm  install  nodemon  -g

Now instead of using the node command to start the server, use  nodemon  as follows:

$ nodemon  index.js

Confirm the server is still respondingHello World!. Change the response string toLife is good! and without stopping and restarting the server, refresh the browser and confirm that the server now responds with the new string. To practice, create another endpoint mapped to the root of the application, e.g.,"/". Navigate to http://localhost:4000 with your browser and confirm the server responds with the message below.

index.js

 

constexpress=require('express')

constapp=express()

app.get('/hello', (req, res) => {res.send('Life is good!')})

app.get('/', (req, res) => {

  res.send('Welcome to Full Stack Development!')})

app.listen(4000)

 

 

//http://localhost:4000/hello responds "Life is good"

//http://localhost:4000 responds "Welcome to Full ..."

2.7 Configuring Node.js to use ES6

So far we've been using the keywordimport to load ES6 modules in our React Web applications, but inindex.js we usedrequire instead to accomplish the same thing. Since Node version 12, ES6 syntax is supported by configuring thepackage.json file and adding a new"type" property with value"module" as shown below in the highlighted text.

package.json

 

{

 "type":"module",

 "name":"kanbas-node-server-app",

 ...

 "scripts": {

  "test":"echo \"Error: no test specified\" && exit 1",

  "start":"node index.js"

 },

 

// type module turns on ES6

 

 

 

 

// usenpm start to start server

Now, instead of usingrequire() to load libraries, the familiarimport statement can be used instead. Here's theindex.js refactored to useimport instead ofrequire. Restart the server, refresh the browser and confirm that the server responds as expected.

index.js

 

importexpressfrom'express';

constapp=express();

app.get('/hello', (req, res) => {res.send('Life is good!')})

app.get('/', (req, res) => {res.send('Welcome to Full Stack Development!')})

app.listen(4000);

2.8 Creating HTTP Routes

Theindex.js file creates and configures an HTTP server listening for incoming HTTP requests. So far we've created a simplehello HTTProute that responds with a simple string. Throughout this and later assignments, we're going to create quite a few other HTTP routes, too many to define them all inindex.js. Move both HTTP routes to theHello.js file created earlier as shown bellow.

index.js

 

importexpressfrom'express';

constapp=express();

app.get('/hello', (req, res) => {

  res.send('Life is good!')

});

app.get('/', (req, res) => {

  res.send('Welcome to Full Stack Development!')

});

app.listen(4000);

 

 

// move this to Hello.js

Copy the routes toHello.js as shown below.

Hello.js

 

console.log('Hello World!');

app.get('/hello', (req, res) => {

   res.send('Life is good!')

});

app.get('/', (req, res) => {

   res.send('Welcome to Full Stack Development!')

});

// don't need anymore

// moved here from index.js

In our caseHello.js handles HTTP requests for ahello greeting and responds with a friendly reply. We're not done though. Notice thatHello.js referencesapp which is undefined in the file. Let's passapp as a parameter in a function we can import and invoke fromindex.js as shown below. Testhttp://localhost:4000/hello from the browser and confirm the reply is still friendly.

Hello.js

 

export default functionHello(app) {

  app.get('/hello', (req, res) => {

    res.send('Life is good!')

  })

  app.get('/', (req, res) => {

    res.send('Welcome to Full Stack Development!')

  })

}

// function acceptsapp reference toexpress module

// to create routes here. We could have used the new

// arrow function syntax instead

ImportHello.js and pass app to the function as shown below.

index.js

 

importexpressfrom'express'

importHellofrom"./Hello.js"

constapp=express()

Hello(app)

app.listen(4000)

 

// importHello fromHello.js

 

// passapp reference toHello

发表评论

电子邮件地址不会被公开。 必填项已用*标注