The project construction process of writing the node backend interface for the first time

Node.js

                                                       Study hard and make progress every day✨                                                   

The http module of node.js supports creating a server. Next we will use it to initialize the server.

Review built-in modules 

1.fs module

The fs module is a module officially provided by Node.js for operating files. It provides a series of methods and properties to meet users' file operation needs. For example:

 fs.readFile() 方法,用来读取指定文件中的内容
 fs.writeFile() 方法,用来向指定的文件中写入内容

If you use fs to operate files, you need to import it in the following way

const fs=require('fs')

2.path path module

The path module is a module officially provided by Node.js for processing paths. It provides a series of methods and attributes to meet users' needs for path processing. For example

 path.join() 方法,用来将多个路径片段拼接成一个完整的路径字符串
 path.basename() 方法,用来从路径字符串中,将文件名解析出来

 If you want to use the path module to process paths in JavaScript code, you need to import it first as follows:

const path=require('path')

3.http module

The http module is a module officially provided by Node.js for creating web servers. Through the http.createServer() method provided by the http module, you can easily turn an ordinary computer into a Web server, thereby providing external Web resource services.

If you want to use the http module to create a web server, you need to import it first

const http=require('http')

 Third-party module & basic project structure construction

prospect preparation

Project folder structure

You can refer to:

image.png

 There are also some necessary third-party libraries that need to be installed.

express
axios
body-parser
cookie-parser
cors
express-art-template
express-session
form-data
jsonwebtoken
multer
path
multiparty
art-template
connect-multiparty
npm i express axios body-parser cookie-parser cors express-art-template express-session form-data jsonwebtoken multer path multiparty art-template connect-multiparty

 Among them, server.js is used as the entry file of the entire project. The contents of the file are

//引入第三方插件
const express = require("express");
const app = express();
const body_parse = require("body-parser");
const path = require("path");
const session = require("express-session");
//安装cors中间件
const cors = require("cors");

// 引入路由

// 配置(解析变量)
app.engine("html", require("express-art-template"));
app.use(body_parse.urlencoded({ extended: false }));
app.use(body_parse.json());
//配置session
app.use(
  session({
    secret: "test",
    cookie: { maxAge: 60 * 1000 * 30 * 24 },
    resave: true,
    saveUninitialized: false,
  })
);
//配置文件
app.use("/public", express.static(path.join(__dirname, "./static")));
app.use(
  "/node_modules",
  express.static(path.join(__dirname, "./node_modules"))
);
app.use(cors());
app.set("views", "views");
// 配置路由

// 启动服务器
app.listen(8099, () => {
  console.log("服务器已启动,端口号:8099");
});

Configuration of common commonly used packages

0. Package management configuration file

The npm package management tool provides a shortcut command that can quickly create the package management configuration file package.json in the directory where the command is executed :

use:

In the project root directory , create a configuration file called package.json , which can be used to record which packages are installed in the project . This makes it easier to share the project's source code among team members after removing the node_modules directory.

Terminal input

npm init -y

The dependencies node in this file records all packages and version numbers installed by the project.

1.express

what is express

Official concept: Express is a fast, open, and minimalist web development framework based on the Node.js platform.

Popular understanding: Express functions similarly to the built-in http module of Node.js, and is specially used to create web servers.

The essence of Express: It is a third-party package on npm that provides a convenient method to quickly create a web server.

Express Chinese website (nodejs.cn)

 Install

Open the project in the integrated terminal

Execute installation command

 npm install express

Basic usage

Write the following code in the project's entry file server.js

// 导入 express 模块
const express = require('express')
// 创建 express 的服务器实例
const app = express()
// 之后的其他配置都写在这里
// 调用 app.listen 方法,指定端口号并启动web服务器
app.listen(8888, function () {
  console.log('server is running at http://127.0.0.1:8888')
})

 2.request

Introduction

I believe that  all Node.js developers will be familiar with Request. This is a Node.js module, provided in the form of npm package. It is a simple HTTP client through which HTTP requests can be easily implemented.

Execute installation command

npm install request --save

3.Axios

Axios is a promise-based HTTP library that can be used in browsers and node.js. Mainly used to send requests to the background.

Official website: Axios Chinese documentation | Axios Chinese website | Axios is a promise-based network request library that can be used in browsers and node.js (axios-http.cn)

Execute installation command

npm install axios -g

4.cheerio

 Execute installation command

npm install cheerio

5.nomailer

Interface used to write and send email verification codes

Introduction:

For details, please refer to: "nodemailer" Node email sending module - Nuggets (juejin.cn) 

 Execute installation command

npm install nodemailer --save

6.mjml

If we need to send email information to users, mjml will come in handy.

MJML is a markup language designed to reduce the pain of writing response emails. For details, please refer to the official website. I won’t go into too much detail here.

Official website: MJML - The Responsive Email Framework

 Execute installation command

npm install mjml

7.mongoose

Note: The prerequisite for using mongoose is that mongodb has been downloaded on the computer.

mongoose is a third-party module based on Node.js for operating MongoDB database.

In short, the mongoose library is a convenient encapsulation for operating the MongoDB database in the node environment. It is an object model tool. Mongoose converts the data in the database into JavaScript objects for use in your application.

Execute installation command

npm i mongoose --save

 8.apidoc

A tool that generates documentation just by writing comments

For specific operation steps, please refer to apiDoc - Super Simple Document Generator - Zhihu (zhihu.com) 

 Execute installation command

npm install apidoc -g

  9.cors

When back-end interaction requires transferring files, cross-domain problems usually occur. We usually use the cors plug-in to solve it. The mdn document is as follows: Cross-origin resource sharing (CORS) - HTTP | MDN (mozilla.org)

 Execute installation command

npm install express

Common errors: Cannot find module 'request'

At this time, you generally need to check whether you have a package management tool, which is package.json. If not, you need to execute the command in the terminal to create it.

npm init -y

If it already exists, execute the command:

cnpm install

 All dependencies in package.json will be downloaded to the node_modules folder, and node server.js can be run.


 In fact, the reason is that when I first started learning the node project, I didn't pay attention to the overall structure of the project. The folders were placed randomly, which made the process structure of the entire project look messy, so I built it again. The senior explained it to us again. I learned a lot from the whole process of the node project. After I came back, I readjusted the placement of the files. My classmates in the group helped me rearrange the placement of the html files, which solved the bug that had been bothering me all morning. It was really great. incredible. From now on, there are some things that you can’t just think about and don’t do, you have to work hard and put into practice, come on!

When you study, you really need to pay attention to your carelessness.

Final words:

                                                       Study hard and make progress every day✨                                                   

Guess you like

Origin blog.csdn.net/www340300/article/details/131743384