Use local JSON server service to create simple local API data

Time:2020-11-25

preface

Recently, I was learning Vue framework. In the process of learning, I found a third-party library similar to mockjs: JSON server. It can not only simulate the perfect interface data, but also modify the type of request to modify the local data. It is a very good library, so share your experience.

Get started quickly

1、 New file to store data

Create a folder on the computer that belongs to JSON server. The folder is mainly used to create and store JSON data. For example: “test JSON”

2、 Initialization package.json

The vscode editor opens the test JSON folder and the terminal input command linenpm initinitialization package.json File, enter the command line and press enter all the time.

Command:

npm init

3、 Create db.json data file

In package.json Create a db.json To design the API data we need. As shown below, we created a simple interface data for:

{
  "users": [
    {
      "name": "joker",
      "age": 22,
      "Sex": Male
    },
    {
      "name": "tom",
      "age": 24,
      "Sex": Male
    },
    {
      "name": "jerry",
      "age": 18,
      "Sex": Male
    }
  ]
}

4、 Install JSON server

Open the IDE terminal and enter the command linenpm install json-server --save-devInstall the local JSON server.

Command:

npm install json-server --save-dev

5、 Configure JSON server to run scripts

After installing JSON server, we need to package.json Configure the script to start the JSON service in.

1.json-server --watch db.json: run the JSON server service and start the local API data.

2.json-server --watch db.json --port 8888: run and start the JSON server service on other local ports (default port 3000).

3.json-server http://jsonplaceholder.typicode.com/db: run start configuration remote mode JSON server service.

"scripts": {
  "json-server": "json-server --watch db.json --port 8888",
  "json-server:remote": "json-server http://jsonplaceholder.typicode.com/db",
},

6、 Run the startup service to get the data

After running the start service command, open postman to get the local API data and check whether the local data runs successfully. As shown in the figure below, the local data obtained by postman is correct:

reference

json-server