Express

Express introduced

  • Express is a third-party module for quickly setting up servers (instead of HTTP modules)
  • Express is a fast, open and minimalist Web development framework based on node. js platform. The same type of product Koa
  • Express retains the basic API of the HTTP module. When using Express, you can also use the HTTP API
    • When using Express, HTTP module methods such as res.end() and req.url can still be used
  • Express also encapsulates new methods that make it easier to build servers
  • Express provides middleware capabilities, and many other powerful third-party modules are developed based on Express
  • Express website

Install express

In the project folder, execute NPM I Express. You can download and install Express.

Note: Express cannot be installed in the Express folder. Otherwise, the installation fails.

Use Express to build a Web server

Steps to build a Web server with Express:

1) Load the Express module 2) Create an Express server 3) start the server 4) listen for browser requests and process themCopy the code
// Use Express to build the web server
// 1) Load the Express module
const express = require('express');

// 2) Create an Express server
const app = express();

// 3) Start the server
app.listen(3000.() = > console.log('Express server is working now'));

// 4) Listen for the browser request and process it

app.get('GET requested address ', processing function); app.post('POST requested address ', processing function);Copy the code

Express encapsulation method

Express is able to build a Web server because it encapsulates the core HTTP module.

After encapsulation, Express provides a very convenient and user-friendly approach.

For example, app.get() and app.post() are new ways to encapsulate Express.

Here’s another res.send() method

  • This method can replace the res.end method in the native HTTP module, and is more useful than res.end
  • Res.send () is used to make a response
  • The content of the response also cannot be numeric
  • If the response is a JS object, then the object is automatically converted to JSON format inside the method.
  • And the content-Type response header is automatically added
  • If you’ve already responded, don’t respond again.
const express = require('express');
const app = express();
app.listen(3006.() = > console.log('Turned on'));

/ / write interface
app.get('/api/test'.(req, res) = > {
  // res.end('hello world, hahaha '); // Response Chinese will be garbled, must own the response header
  // res.end(json.stringify ({status: 0, message: 'registered successfully'})); // Can only respond to string or buffer types

  // Express provides the send method to solve the above two problems
  res.send({ status: 0.message: 'Registration successful' }); // The send method automatically sets the response header; And it automatically converts the object to a JSON string
});
Copy the code

After use nodemon command to run the above code, you can use http://localhost:3000/api/test request interface.

The global module Nodemon

When the server code changes, you have to restart the service, which is very troublesome.

Nodemon is a global module. After installation, you can use Nodemon to run JS files instead of Node.

The advantage is that when the code is saved, Nodemon will detect if the file code has changed, and if it has, it will automatically restart the server.

Install Nodemon globally

npm i nodemon -g
Copy the code

use

nodemon xxx.js
Copy the code

By using the nodemon command instead of the Node command, we can concentrate on developing the code without having to restart the service.

You are advised not to abuse nodemon. You are advised to use nodemon only when starting the service. Otherwise, continue to use Node.

Interface test tool

You can only test the interface in GET mode by using a browser. If the interface is POST, the browser test cannot be used.

So you need a professional tool to test the interface.

Common interface testing tools:

  • Postman (default English version, Github has Chinese package)
  • Apifox (Default Chinese)

Both programs are similar in usage and are relatively simple. Here is Apifox.

  • First, log in to Apifox. Those without an account need to register first

  • Click “Project” in the sidebar to create a new project

  • On the Project page, options go to the project interface

Send a GET request

Send a POST request

Write the interface

The purpose of writing interfaces is to experience how interfaces are written at the back end. So write the simplest interface you can.

  • Create a backend interface project folder, such as Code
  • Download and install the required module Express

Create index. Js

Create index.js to write back-end code and start the service.

The module used is Express.

The original code can be copied and modified on the official website

// Start the service and write the interface
const express = require('express')
const app = express()

/ / write interface
// app. request mode (' interface address ', 'handler with req, res ');
// app.get('/api/student', (req, res) => {});
// app.post();
// app.delete();
// app.put();


app.listen(3000.() = > console.log('Turned on'));

Copy the code

With just a few lines, you can start the service using Nodemon index.js.

Encapsulate modules that manipulate JSON

  • Prepare the JSON file to store the data (db.json).
  • Have a custom module ready to handle JSON files.

Preparing the JSON file

In real development, data is usually stored in a database, and most front-end programmers do not understand databases.

So, we can use JSON files to store data. (Use JSON files instead of databases for further development)

Create db. Json file as follows:

[{"id": 1."bookname": Journey to the West."author": "Cheng 'en Wu"."publisher": "Beijing Press"
  },
  {
    "id": 2."bookname": A Dream of Red Mansions."author": "Cao Xueqin"."publisher": Shanghai Publishing House
  },
  {
    "id": 5."bookname": "Water Margin"."author": "Nai am"."publisher": "Tsinghua Press"
  },
  {
    "id": 12."bookname": Romance of The Three Kingdoms."author": "Luo Guanzhong"."publisher": "Business Press"}]Copy the code

Encapsulates modules that manipulate JSON files

To facilitate the query, add, modify, and delete data in the JSON file. We encapsulate a custom module ourselves

  • Create your own json-parser.js file

  • We can use then-FS for encapsulation.

  • By convention, each method returns a Promise object (for convenience, the query method Query can return query data)

  • Later, results can be obtained via.then or async and await.

  • That way, you can see how Promise is used.

The code is as follows:

const { join } = require('path');
const fs = require('then-fs');

// Splice the file path
const filename = join(__dirname, 'db.json');

// ------------------ Obtain data ----------------------
async function query() {
  let data = await fs.readFile(filename, 'utf-8');
  return JSON.parse(data);
}

// ------------------ Add data ----------------------
async function add(row) {
  let res = await query();
  let id = res[res.length - 1].id + 1;
  row.id = id;
  res.push(row);
  return fs.writeFile(filename, JSON.stringify(res));
}

// ------------------ Delete data ----------------------
async function del(id) {
  let res = await query();
  let result = res.filter(item= >item.id ! = id);return fs.writeFile(filename, JSON.stringify(result));
}

// ------------------ Modify data ----------------------
async function update(row) {
  let res = await query();
  let index = res.findIndex(item= > item.id == row.id);
  res.splice(index, 1, row);
  return fs.writeFile(filename, JSON.stringify(res));
}


/ / export
module.exports = { query, add, del, update };


Copy the code

Access to books Interface

  • Interface name: / API/getBooks
  • Request mode: GET
  • Request parameters: None
  • Response data:{status: 0, message: 'get books successfully ', data: [{a book}, {a book}]}

The basic code is as follows:

const { query, add, del, update } = require('./json-parser'); // Import the module that handles JSON files

app.get('/api/getbooks'.async (req, res) => {
  let data = await query();
  res.send({ status: 0.message: 'Book acquisition success', data });
})
Copy the code

Next, you can use the client to send request detection.

Adding a Book Interface

  • Interface name: / API /addbook
  • Request mode: POST
  • Request body: BookName, Author, Publisher
  • Content-Type: application/x-www-form-urlencoded
  • Response data:{status: 0, message: 'Add book successfully'}

The basic code is as follows:

// Configure to receive the request body
app.use(express.urlencoded({ extended: true })); // Receive the query string format request body


app.post('/api/addbook'.async (req, res) => {
  let row = req.body;
  let r = await add(row);
  if (r === undefined) {
    res.send({ status: 0.message: 'Added successfully'})}})Copy the code

Next, you can use the client to send request detection.

Modifying the Book Interface

  • Interface name: / API /updatebook
  • Request mode: PUT
  • Request body: ID (id), BookName (title), Author (author), Publisher
  • Content-Type: application/x-www-form-urlencoded
  • Response data:{status: 0, message: 'Modify book successfully'}

So:


app.put('/api/updatebook'.async (req, res) => {
  let row = req.body;
  let r = await update(row);
  if (r === undefined) {
    res.send({ status: 0.message: 'Modified successfully'})}})Copy the code

Next, you can use the client to send request detection.

Delete book interface

  • Interface name: / API /delbook
  • Request mode: DELETE
  • Request parameter: id (id)
  • Response data:{status: 0, message: 'Delete book successfully'}

So:

app.delete('/api/delbook'.(req, res) = > {
    let id = req.query.id;
  	obj.del(id)
    res.send({ status: 0.message: 'Deleted book succeeded'})});Copy the code

Next, you can use the client to send request detection.

Test the interface using front-end code

The front end sends Ajax requests to the interface. There will be cross-domain problems.

Cross-domain solutions can be used here using the CORS scheme.

The back-end

  • Install the CORS module. npm i cors

  • In the code, before all interfaces are loaded, cORS is registered as middleware.

    let cors = require('cors')

    app.use(cors())

The front end

Send the request normally.

<script src="./axios.js"></script>
<script>
  axios.get('http://localhost:3000/api/getbooks').then(result= > {
    console.log(result);
  });
</script>
Copy the code