nodejs express(1)

foreword

insert image description here

Express is one of the modules that nodejs must learn. Starting from this article, we will introduce some basic content of express, express installation, restful interface specification, express interface development, express cross-domain processing, express middleware use, request information req Common processing, request header res common processing, etc. Prepare for the next real project framework to develop an express server.

express introduction

Express is developed on the basis of the built-in module http of nodejs, that is to say, all the APIs of the http module and express are available, and their usage is very similar.

The advantage of express.js is that it encapsulates some commonly used interface processing methods, which is more conducive to the expansion of middleware and makes the development of interfaces more standardized and reasonable.

Install

express is not a built-in module of nodejs, but a third-party open source module, which needs to be downloaded and installed if you want to use it.

To be deployed to the server in the future, it needs to be used in both the development environment and the production environment, enter the command line

npm install express --save 或者 yarn add express

During the development process, we will find that we have been writing the code of the server. After each modification, the original server needs to be shut down and restarted node express.jsto effect.

To this end, install an auxiliary npm package nodemon, nodemon can automatically monitor the update of the file, and automatically restart.

npm install -g nodemon 或者 yarn global add nodemon 

After the installation is complete, let's restart the server, so we don't need to restart every time we change the code

nodemon express.js

RESTful interface specification

Since we want to develop a server, we must follow the interface development specification. Here is a brief introduction to the RESTful interface design specification.

  1. Try to use httpsthe agreement, if the conditions do not support, you can only httpuse the agreement
  2. You should try to put all APIs under the dedicated domain name. For example https://api.dengxi.com, of course, if your interface is relatively simple and your business is not complicated, you can use the main domain name + . '/api'For example, if the domain name of the website is http://dxyx-together.cn, then all APIs are placed In http://dxyx-together.cn/api/xxx, the following xxx is the specific path of the api.
  3. Version number, if it is a proprietary domain name https://api.dengxi.com, the current version is v1, then correspondingly https://api.dengxi.com/v1, if it is not a proprietary domain name, put the version information in the response header, which may not be as intuitive as putting it directly on the url.
  4. The path name, also known as the endpoint, does not allow verbs in English, but should be plural nouns. For example, if there is an interface that returns information about many users, it should be designed as xxx/api/users. If the returned data is directly the content of a database table, it can be named directly after the database table name.
  5. There are five commonly used interfaces get(获取数据),post(创建数据),delete(删除数据),put(完整更新数据),patch(某一数据部分更新), and two are not commonly used (head,options). In many cases, these interface types can be mixed, but according to the specification, they have their own usage scenarios.
  6. Authentication. Part of the interface involves account information, such as common mid- and back-end management systems, and the c-side also has scenarios such as shopping carts, member centers, and wallets, and JWT-based interface authority authentication.
  7. Cross-domain processing, set cors cross-domain processing on the server side, allowing clients to request resources across domains, especially when the interface is placed under a dedicated domain name.
  8. For each request of each interface, the server must give the HTTP status code response and data two parts.
  9. HTTP status codes are divided into five 1xx(相关信息) 2xx(操作成功) 3xx(重定向) 4xx(客户端错误) 5xx(服务器错误)categories There are more than 100 status codes, and more than 20 are commonly used.
  10. The returned data part is usually a JSON object. Therefore, the server returns the header and needs to Content-Typeset the attribute toapplication/json
  11. Error handling mainly requires the correct use of http status codes, mainly 4xx and 5xx, and the returned information is as detailed as possible for faster troubleshooting.

Simple use of express

The simplest server can be implemented with just a few lines of code.

//express.js
var express = require("express");
var app = express();
var port = 3000;

app.get("/", function (req, res) {
    
    
  res.send("hello world");
});

app.listen(port, function () {
    
    
  console.log("server runing at 3000");
});

Enter the command line again, and the server starts successfully

nodemon express.js

Five interface types of restful specification

var express = require("express");
var app = express();
var port = 3000;

app.get("/", function (req, res) {
    
    
  var query = req.query
  console.log(query)
  res.send("hello world");
});

app.post("/", function (req, res) {
    
    
  res.send("post hello world");
});

app.put("/users",function(req,res) {
    
    
    res.send("put hello world");
})

app.delete("/users",function(req,res) {
    
    
    res.send("delete hello world");
})

app.patch("/users",function(req,res) {
    
    
    res.send("delete hello world");
})

app.listen(port, function () {
    
    
  console.log("server runing at 3000");
});

Acquisition of request information req

For example, we get the parameter req.query of the get request

//express.js
var express = require("express");
var app = express();
var port = 3000;

app.get("/api", function (req, res) {
    
    
  console.log(req.query)
  res.status('200')
});

app.listen(port, function () {
    
    
  console.log("server runing at 3000");
});

insert image description here
insert image description here
About all properties and methods of req, you can find here

http://expressjs.com/en/5x/api.html#req

Chinese version
http://expressjs.com/zh-cn/4x/api.html#req

Setting of response information res

var express = require("express");
var app = express();
var port = 3000;

app.get("/api", function (req, res) {
    
    
  var query = req.query
  console.log(query)
  res.set('Content-Type', 'application/json')
  res.status('200')
  res.json({
    
    code:200,data: '请求成功了'})
});

app.listen(port, function () {
    
    
  console.log("server runing at 3000");
});

insert image description here
insert image description here
About all properties and methods of res, you can find here
http://expressjs.com/en/5x/api.html#res

Chinese version
http://expressjs.com/zh-cn/4x/api.html#res

Use of middleware

Express officially provides several important middleware
http://expressjs.com/en/5x/api.html#express

For example express.json(), when the data sent by the client is json data, req.body cannot get normal data, so we need to process it through this middleware.

I use the http module to request my express server

const http = require("http");

// 请求刚刚创建的服务器
const options = {
    
    
  hostname: "localhost",
  port: 3000,
  path: "/api",
  method: "post",
  headers: {
    
    
    "Content-Type": "application/json",
  },
};

const req = http.request(options, (res) => {
    
    
  console.log(`状态码: ${
      
      res.statusCode}`);
  console.log(`响应头: ${
      
      JSON.stringify(res.headers)}`);
  res.setEncoding("utf8");
  res.on("data", (chunk) => {
    
    
    console.log(`响应主体: ${
      
      chunk}`);
  });
  res.on("end", () => {
    
    
    console.log("响应中已无数据。");
  });
});
req.write(JSON.stringify({
    
     name: "dx" })) // 发送了一个json数据
req.end();

app.useCall the middleware through to achieve the purpose of global use

var express = require("express");
var app = express();
var port = 3000;

app.use(express.json())

app.post("/api", function (req, res) {
    
    
  console.log(req.body)
  res.set('Content-Type', 'application/json')
  res.status('200')
  res.json({
    
    code:200,data: '请求成功了'})
});

app.listen(port, function () {
    
    
  console.log("server runing at 3000");
});

insert image description here
It is also possible to use middleware alone in an interface, and only take effect for this interface.

var express = require("express");
var app = express();
var port = 3000;

// app.use(express.json())

app.post("/api", express.json(), function (req, res) {
    
    
  // var query = req.query
  console.log(req.body)
  res.set('Content-Type', 'application/json')
  res.status('200')
  res.json({
    
    code:200,data: '请求成功了'})
});

app.listen(port, function () {
    
    
  console.log("server runing at 3000");
});

custom middleware

The essence of middleware is actually a function. The express middleware function has three parameters, req, res, next

Create a middleware to print the log, so that the body of each client request can be seen in the log, which is used to simplify the previous solution.

function (req, res, next) {
    
    
  console.log(req.body);
  // 执行下一个中间件,必须调用,否则请求会被拦截在这里
  next();
}

Create another middleware to satisfy the response, always return status 200 and return the same json

function (req, res, next) {
    
    
  res.set("Content-Type", "application/json");
  res.status("200");
  res.json({
    
     code: 200, data: "请求成功了" });
  // 执行下一个中间件,必须调用,否则请求会被拦截在这里
  next();
}

Use these two middleware

var express = require("express");
var app = express();
var port = 3000;

app.use(express.json());

app.use(function (req, res, next) {
    
    
  console.log(req.body);
  next();
});

app.use(function (req, res, next) {
    
    
  res.set("Content-Type", "application/json");
  res.status("200");
  res.json({
    
     code: 200, data: "请求成功了" });

  next();
});
// app.post 里面啥也没干
app.post("/api", express.json(), function (req, res) {
    
    
});

app.listen(port, function () {
    
    
  console.log("server runing at 3000");
});

On the left is the server interface, which prints the name:dx sent by the client, and on the right is the client request, and also gets the status code 200 and json data.
insert image description here

The execution order of middleware is executed sequentially from top to bottom, and the order of execution is also very important.
If it is a middleware of a single interface, middleware 1 is executed before middleware 2.

app.post("/api", 中间件1, 中间件2, function (req, res) {
    
    
});

Solve cross-domain

In a crude way, any domain name can be requested successfully.

var express = require("express");
var app = express();
var port = 3000;

//设置允许跨域访问该服务.
app.all("*", function (req, res, next) {
    
    
  res.header("Access-Control-Allow-Origin", "*"); // *表示所有域名,你也可以指定某个特别的域名 "www.dxyx-together.cn"
  res.header("Access-Control-Allow-Headers", "Content-Type");
  res.header("Access-Control-Allow-Methods", "*"); // *表示所有请求方式都可以跨域,你也可以设置 比如只允许get和post "GET;POST"
  res.header("Content-Type", "application/json;charset=utf-8"); 
  next();
});

app.use(express.json());

app.use(function (req, res, next) {
    
    
  console.log(req.body);
  next();
});

app.use(function (req, res, next) {
    
    
  res.set("Content-Type", "application/json");
  res.status("200");
  res.json({
    
     code: 200, data: "请求成功了" });

  next();
});

app.post("/api", express.json(), function (req, res) {
    
    });

app.listen(port, function () {
    
    
  console.log("server runing at 3000");
});

2. Express's cors Cross-domain
cors is a third-party middleware of Express. By installing and configuring cors middleware, you can easily solve cross-domain problems. The
steps are divided into three steps

  1. run npm install corsinstall middleware
  2. const cors = require('cors')Import middleware using
  3. Call app.use(cors())the configuration
var express = require("express");
var cors = require('cors')
var app = express();
var port = 3000;

//设置允许跨域访问该服务.
app.use(cors())

app.use(express.json());

app.use(function (req, res, next) {
    
    
  console.log(req.body);
  next();
});

app.use(function (req, res, next) {
    
    
  res.set("Content-Type", "application/json");
  res.status("200");
  res.json({
    
     code: 200, data: "请求成功了" });

  next();
});

app.post("/api", express.json(), function (req, res) {
    
    });

app.listen(port, function () {
    
    
  console.log("server runing at 3000");
});

For more usage methods of cors, please refer to the official introduction of the cors plugin
https://www.npmjs.com/package/cors

Other content related to nodejs

nodejs commonjs introduces
nodejs fs module introduces
nodejs path module introduces
nodejs events module introduces
nodejs http module introduces
nodejs net module introduces
nodejs url module introduces
nodejs process module introduces
nodejs buffer module introduces
nodejs stream module introduces

Guess you like

Origin blog.csdn.net/glorydx/article/details/129556381