Translation | "JavaScript Everywhere" Chapter 3 Web Application with Node and Express (^_^)

Translation | "JavaScript Everywhere" Chapter 3 Web Applications with Node and Express

Write at the top

Hello everyone, I am Mao Xiaoyou, a front-end development engineer. An English technical book is being translated.

In order to improve everyone's reading experience, the structure and content of sentences have been slightly adjusted. If you find any flaws in this article, or if you have any comments or suggestions, you can leave a message in the comment area, or add my WeChat: code_maomao, welcome to communicate and learn from each other.

(σ゚∀゚)σ…:*☆Oh, good

Chapter 3 Web Applications with Node and Express

Before implementing our API, we will build a basic server-side web application to serve as the basis for our API backend. We will use the Express.js framework , the "minimalist web framework for Node.js", which means it doesn't have many features but is highly configurable. We will use Express.js as the basis of the API server, but Express can also be used to build full-featured server-side web applications.

User interfaces (such as websites and mobile applications) communicate with web servers when they need to access data. These data can be anything from the HTML required to render the page in the Web browser to the user's search results. The client interface uses HTTP to communicate with the server. The data request is sent from the client to the web application running on the server via HTTP. Then, the web application processes the request again via HTTP and returns the data to the client.

In this chapter, we will build a small server-side web application, which will become the basis of our API. For this, we will use the Express.js framework to build a simple web application that sends basic requests.

Hello World

Now that you understand the basics of server-side web applications, let's get started. In the src directory of our API project, create a file named index.js and add the following content:

const express = require('express');
const app = express();
app.get('/', (req, res) => res.send('Hello World'));
app.listen(4000, () => console.log('Listening on port 4000!'));

In this example, first we need the express dependency and express .jscreate the app object using the imported module.

Then, we use the get method of the app object to direct our application to send a response when the user visits the root URL (/) “Hello World”.

Finally, we direct the application to run on port 4000. This will allow us to view the application locally via the URL http://localhost:4000.

Now to run the application, enter the following command in your terminal node src/index.js.

After doing this, you should see a log in the terminal, which reads and listens on port 4000.

If so, you should be able to open a browser window and see the result at http://localhost:4000

Figure 3-1.

[External link image transfer failed. The origin site may have an anti-leech link mechanism. It is recommended to save the image and upload it directly (img-EUayHeLf-1605805770495)(https://i.loli.net/2020/11/19/jft5eHG7cP6lkLE.png )]

Figure 3-1. The result of our Hello World server code in the browser

Nodemon

Now, suppose the output of this example does not properly express our excitement. We want to change the code to add an exclamation mark in the response. Continue to perform the operation and change res.sendthe value to Hello World!!now a complete line should be:

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

If you go to the web browser and refresh the page, you will notice that the output has not changed. This is because any changes we make to the web server require us to restart it. To do this, switch back to your terminal and press Ctrl + C来Stop Server.

Now, restart it by typing it again node index.js.

Now, when you switch back to the browser and refresh the page, you should see the updated response.

You can imagine how tedious it can be to stop and restart our server for each change.

Thankfully, we can use the Node package nodemon to automatically restart the server when changes occur. If you see the package.jsonfile for this project , you can scriptssee a devcommand in the object that instructs to nodemonmonitor the index.js file:

"scripts": {
    
      ...  "dev": "nodemon src/index.js"  ...}

package.json Scripts

There are some other auxiliary commands in the scripts object. We will discuss it in later chapters.

Now, to start the application from the terminal, enter:

npm run dev

Switch to the browser and refresh the page, you will see everything is normal. To confirm nodemon automatically restart the server, let us once again renew our res.sendvalues, it appears as:

res.send('Hello Web Server!!!')

You should now be able to refresh the page in your browser and see the update without having to restart the server manually.

Expansion port options

Currently, our application is running on port 4000. This is very useful for local development, but when deploying the application, we need to flexibly set it to other port numbers. Let us take steps to replace this immediately. We will portstart by adding a variable:

const port = process.env.PORT || 4000;

This change will allow us to dynamically set the port in the Node environment, but fall back to port 4000 if the port is not specified. Now let's adjust

app.listenCode to use this change and use console.logto output the correct port:

app.listen(port, () =>  console.log(`Server running at http://localhost:${
      
      port}`));

Now, our final code should be:

const express = require('express');

const app = express();
const port = process.env.PORT || 4000;

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

app.listen(port, () =>
  console.log(`Server running at http://localhost:${
      
      port}`)
);

In this way, we now understand the basics of code that can start and run a web server. If everything is normal in the test, please make sure that there are no errors in the console, and then reload the web browser at http://localhost:4000 .

in conclusion

Server-side web applications are the foundation of API development. In this chapter, we Express.jsbuilt a basic web application using the framework. When developing Node-based web applications, you can choose a variety of frameworks and tools. Express.js's flexibility, community support and maturity as a project is a good choice. In the next chapter, we will turn our web application into an API.

Translator language and book details

If there is any inadequate understanding, please correct me. If you think it's okay, please like to collect or share it, hoping to help more people.

Guess you like

Origin blog.csdn.net/code_maomao/article/details/109832604