Use koa2 to build web background api interface

Goal: Use koa2 to build an api interface to provide data for the front end

Realize the effect:

Enter the interface address to query the corresponding interface data, and enter http://127.0.0.1:3000/api/map to query the distribution of merchants. When you enter http://127.0.0.1:3000/api/seller , query the seller’s product sales.

 

The whole project can be divided into two steps:

1: Build the project framework and download the installation package.

2: Create middleware to realize interface functions.

 

Before building the project framework, you first need to install node.js, installation tutorial: https://www.runoob.com/nodejs/nodejs-install-setup.html

 

Step 1: Build the project framework

Use vscode to create a project and write code, open vscode, and create a project folder (koa_server) to store the project code.

Create three folders in the koa_server folder: data (used to store json data), middleware (storage middleware), utils (storage tools)

Then create the project's startup (entry) file app.js

After the file is created, start downloading the installation package. Enter the following command line in the terminal (the key above the shortcut key ctrl+tab to call up the terminal):

npm init -y

npm install koa

npm i koa2-cors --save

The first command is to create the project configuration file, the second command is to install the dependency package of koa2, and the third command is to install the dependency package of koa2-cors (used for cross-domain requests).

After the above two commands are executed, the project structure is shown in the following figure:

 

Step 2: Write code to realize data query function

Create three files in the middleware folder, namely koa_response_data.js, koa_response_duration.js, koa_response_header.js

These three files represent three middleware:

koa_response_data.js: middleware for processing business logic, reading data from a json file

 

koa_response_duration.js: Middleware for calculating server consumption time

 

koa_response_header.js: middleware for setting response headers

 

Next, create a tool method, create a file_utils.js file in the utils folder, read the data of the json file, and return it to the middleware.

 

After the above code is written, the function of app.js is completed. In the entry file, four things need to be completed: create an instance of koa, bind middleware, bind port number, and allow cross-domain requests.

 

 

After all the above function codes are written, you can test whether the interface is available.

Enter node app.js in the terminal to start the service

Use the tool (ApiPost) to test:

 

So far, the interface development is complete.

The complete project code can be downloaded from my code cloud:  https://gitee.com/lm888888/koa_server

Guess you like

Origin blog.csdn.net/liangmengbk/article/details/109964133