preface

Ajax is a must-learn at the front end, but students new to Ajax may be frustrated by the lack of interface testing.

This primer will take you 10 minutes to solve the problem of no interface tests, and no back-end knowledge is required.


If you don’t want to build your own native environment, you can also use several online interface platforms recommended in Free Online APIS for front-end needs, which include common JSON structured data and images.


While free interfaces on the wire can be tested, native analog data is more suitable for front-end developers when they need to customize interfaces and data.


This paper is divided into introductory and advanced chapters. Slide down a bit further to see the full contents.


Introduction: within 5 minutes with you to achieve the local environment to build and add, delete, change, check operations to meet the use of the entry test.

Advanced: This chapter mainly explains common query operations, including general configuration, static resource configuration and other knowledge points. This section is a bit long, I suggest a collection.


In this paper, agreed

  1. The main readers of this article areThe front whiteThere is very little back-end knowledge involved, so I’m not going to cover itJson - server middlewareThe content of the.
  2. All of the information covered in this article will be provided with the corresponding code presentation (which is more detailed than the official documentation).
  3. This article USES thepostmanTest, hoping to accommodate readers who use different libraries to make data requests (I know there are only ones that knowjQueryDeveloper).
  4. Special cases will be usedaxiosWork with the demo.


Like + favorites = learned


directory











An introduction to

Json – server profile

NPM address | making address


Get a full fake REST API with zero coding in less than 30 seconds (seriously)

A complete set of simulated REST apis can be obtained in 30 seconds.


Using jSON-server requires following certain specifications.

  • Data query to useGET.
  • New data to be usedPOST.
  • Delete data to useDELETE.
  • Modifying data usagePUTPATCH.


Other verbose introductions can be found at the web site provided above.


For 30 seconds to start

Start in 30 seconds and complete in 4 steps:

  1. nodeEnvironmental installation
  2. The installationjson-server
  3. Create a databasejsonFile)
  4. Start the service


1. Node environment installation

Json-server needs to be downloaded through NPM, which depends on Node.

There are two common node installation methods. The first is an official download and the second is an NVM download. Just pick one.

Node official website, click to enter the home page to download, after downloading, press “Next” and “Finish”.


Note: Node must be 12 or older. Otherwise, the following error will be reported:

json-server requires at least version 12 of Node, please upgrade
Copy the code


2. Install the json – server

It can be installed globally or within a project. A global installation is recommended because you may become dependent on jSON-server in the future.

Global installation mode:

npm install -g json-server
Copy the code


3. Create a database

Create a folder on your machine, create a new JSON file, and fill it with data.

It is recommended that the file name do not contain Chinese characters.

Ex. :

Create a jSON-server-demo folder, and create a db.json file in json-server-demo (you can name these folders and files freely).

Db. Json file input the following data (data from jSON-server official documentation, you can also use your own data)

{
  "posts": [{"id": 1."title": "json-server"."author": "typicode"}]."comments": [{"id": 1."body": "some comment"."postId": 1}]."profile": {
    "name": "typicode"}}Copy the code


4. Start the service

Go to the json-server-demo directory, open the terminal, and run the following command

json-server --watch db.json
Copy the code


The home page and three interfaces can be directly accessed in the browser, open yourself to try it.

Deal with!





Check (get)

Json-server requires the GET method to query data.

Entry only write a query method, other query operations please go down, see the next step.


The previous section created three interfaces that allow you to retrieve data directly from the browser, Postman, or by writing your own JS code.

http://localhost:3000/posts
Copy the code


http://localhost:3000/comments and http://localhost:3000/profile two interfaces can be trying, here no longer wordy.





Add (post)

The POST method is used to add data to the JSON-server.

Example: Add a new data to posts.

http://localhost:3000/posts
Copy the code


The POSt method is used to transmit data to /posts interface. The original data structure of /posts contains three fields: ID, title and author. Id is automatically added to the primary key by default.


If you open the db.json file, you can see that there is an extra piece of data in posts.


Note that jSON-server does not limit the format and type of data you upload by default, so you need to strictly follow your own data format to add and modify it.





Delete (delete)

Json-server Deletes data using the DELETE method.

The formula for deletion is:

http://localhost:3000/{Interface name}/{id}Copy the code


Let’s say you want to delete the data you just uploaded

{"title": "leihou", "author": "thunder monkey ", "id": 2}Copy the code

You can see that the data you just uploaded has an ID of 2


http://localhost:3000/posts/2
Copy the code


When you open db.json, you will find that the data you just deleted is gone.


Note that Status returns 200 if the deletion succeeds; A 404 is returned if the deleted data does not exist.

I did a simulation with Axios.

The following result is returned after successful deletion:


The following result is returned when the deletion fails:





Change (PUT and patch)

There are two methods for modifying data:

  • putCovered:
  • patchUpdate:


The formula is as follows:

http://localhost:3000/posts/{id}
Copy the code


Overlay (PUT)

Example: Change data with id 1 to {“title”: “leihou”, “author”: “thunder monkey”}

When you open db.json, you can see that the data with ID 1 has changed.


Note: The original data contains title and author. If you use PUT, you must write both fields, otherwise the fields that are not passed will be deleted. That’s what “cover” means.


Such as:


A look at db.json at this point will reveal that the data has been overwritten


Patch update

Restore the data first, as shown in the following figure:

There are title and Author fields.


For example, the patch method is used to change the value of the title field of data 1 to Hello.


If you open the db.json file and check it, you will find that only the title value with id 1 is changed, and the data of the author field is not deleted.











The advanced

Launch parameters

We started the interface project with json-server –watch db.json, where json-server is the command to start the service, –watch is the parameter, and db.json is the target file.


To view the configuration items, run the following command:

Json-server --help # or use the shorthand json-server-hCopy the code


parameter shorthand instructions
–config -c Specifying a configuration file
–port -p The port number
–host -H The host address
–watch -w Monitor file
–routes -r Specifying routing files
–middlewares -m Specified middleware
–static -s Setting up static files
–read-only –ro read-only
–no-cors –nc Cross-source resource sharing is disabled
–no-gzip –ng Ban GZIP
–snapshots -S Setting a Snapshot Directory
–delay -d Setting feedback Delay (MS)
–id -i Setting the id attribute for data (e.g. _id)
–foreignKeySuffix –fks Set the foreign key suffix (for example, _id in post_id)
–quiet -q Disable the output of log messages
–help -h Display help information
–version -v Display version number








configuration

Use jSON-server –help to view all configuration items. Next, I’ll demonstrate a few common configuration operations.


port

Use -por –port to configure the port number, for example, port 6666

json-server -p 6666 db.json
Copy the code


After the start

\{^_^}/ hi!

Loading db.json
Done

Resources
http://localhost:6666/posts
http://localhost:6666/comments
http://localhost:6666/profile

Home
http://localhost:6666
Copy the code





The host address

Json - server - the host 0.0.0.0 db. JsonCopy the code

Set 0.0.0.0 and access via the local IP. Other devices on the same LAN can also be accessed through this address.








Common query operations

Query is the most common operation in daily projects, so query is the focus.


Common query

The one that started in 30 seconds.


Query /posts all data

http://0.0.0.0:3000/posts
Copy the code


Query /comments all data

 http://localhost:3000/comments
Copy the code


Query /profile all data

http://localhost:3000/profile
Copy the code





The id

Modify the contents of db.json.

{
  "posts": [{"id": 1."title": Article 111 ""."author": "Zhang"
    },
    {
      "id": 2."title": Article 222 ""."author": "Bill"}}]Copy the code

At this point, there is only the Posts interface, which contains two pieces of data with ids 1 and 2 respectively.


The query formula is:

http://localhost:3000/posts/{id}
Copy the code


Query data whose ID is 2

http://localhost:3000/posts/2
Copy the code





Conditions of the query

Prepare the following data.

{
  "posts": [{"id": 1."title": Article 111 ""."author": "Zhang"
    },
    {
      "id": 2."title": Article 222 ""."author": "Bill"
    },
    {
      "id": 3."title": Article 333 ""."author": "Zhang"}}]Copy the code

You can see that there are two pieces of data for Joe and one piece of data for Joe.


Single condition query

Find all data whose author is John.

The query author is John’s data

http://localhost:3000/posts?author= zhang SANCopy the code

Add a behind http://localhost:3000/posts? “, and then write the filter criteria.


Multi-condition query (and)

The data above, there are two triple.

This time we will filter the data from author = 3 and title = article 333

Zhang SAN & http://localhost:3000/posts?author= title = article 333Copy the code

When qualifying, use the ampersand sign to add conditions.


Multi-condition query (or)

Title = 222 and title = 333

Article 222 & http://localhost:3000/posts?title= title = 333Copy the code

Using title again and again will screen out everything that fits the criteria.

Of course, we can also use fuzzy queries to achieve similar results, which we’ll talk about later.


Deep attribute query

Here’s another piece of data to show this.

The data content is as follows

{
  "posts": [{"id": 1."title": Article 111 ""."authorInfo": {
        "name": "Zhang"."age": 20}}, {"id": 2."title": Article 222 ""."authorInfo": {
        "name": "Bill"."age": 24}}}]Copy the code

You can see that there are child attributes in authorInfo.


Select * from authorinfo. name where authorinfo. name = author3;

http://localhost:3000/posts?authorInfo.name= zhang SANCopy the code

The child data needs to be accessed using., a bit like the way JS uses dot syntax to access object properties.

I don’t come across many such interfaces at work.





Paging query

Data is paginated with _page and _limit(optional). Note that both _page and _limit should be preceded by underscores.

  • _page: the page number
  • _limit: Data volume per page


Modify the data in db.json to test paging, as shown below

{
  "comments": [
    { "id": 1, "body": "some comment 1", "postId": 1 },
    { "id": 2, "body": "some comment 2", "postId": 1 },
    { "id": 3, "body": "some comment 3", "postId": 2 },
    { "id": 4, "body": "some comment 4", "postId": 3 },
    { "id": 5, "body": "some comment 5", "postId": 1 },
    { "id": 6, "body": "some comment 6", "postId": 3 },
    { "id": 7, "body": "some comment 7", "postId": 3 },
    { "id": 8, "body": "some comment 8", "postId": 1 },
    { "id": 9, "body": "some comment 9", "postId": 2 },
    { "id": 10, "body": "some comment 10", "postId": 2 },
    { "id": 11, "body": "some comment 11", "postId": 3 },
    { "id": 12, "body": "some comment 11", "postId": 1 }
  ]
}
Copy the code

Twelve pieces of data were prepared.


Data on page 2 need to be obtained, with 3 items per page:

http://localhost:3000/comments?_page=2&_limit=3
Copy the code


In addition to the data to be returned, the total amount is returned in Headers; The first, the previous, the next, the last link. Let me make a request with Axios to demonstrate this.

axios.get('http://localhost:3000/comments', {
  params: {
   _page: 2,
   _limit: 3
  }
})
  .then(res => {
    console.log(res)
  })
  .catch(err => {
    console.error(err)
  })
Copy the code

The result is as follows


X-total-count Indicates the total number of stores.


The link field stores the first, the previous, the next, and the last link address

" <http://localhost:3000/comments? _page=1&_limit=3>; rel=\"first\", <http://localhost:3000/comments? _page=1&_limit=3>; rel=\"prev\", <http://localhost:3000/comments? _page=3&_limit=3>; rel=\"next\", <http://localhost:3000/comments? _page=4&_limit=3>; rel=\"last\" "Copy the code





Sorting query

You need to add the sort flag (_sort), and then set the collation rule (_order).

There are ascending order (ASC) and descending order (DESC).

http://localhost:3000/{interface name}?_sort= name of field to sort &_order= sort ruleCopy the code


Take this data:

{
  "comments": [
    { "id": 11, "body": "some comment 1", "postId": 1 },
    { "id": 2, "body": "some comment 2", "postId": 1 },
    { "id": 3, "body": "some comment 3", "postId": 2 },
    { "id": 10, "body": "some comment 4", "postId": 3 },
    { "id": 7, "body": "some comment 5", "postId": 1 },
    { "id": 6, "body": "some comment 6", "postId": 3 },
    { "id": 5, "body": "some comment 7", "postId": 3 },
    { "id": 8, "body": "some comment 8", "postId": 1 },
    { "id": 9, "body": "some comment 9", "postId": 2 },
    { "id": 4, "body": "some comment 10", "postId": 2 },
    { "id": 1, "body": "some comment 11", "postId": 3 },
    { "id": 12, "body": "some comment 11", "postId": 1 }
  ]
}
Copy the code

The sorting of ids is messy, and if the data is requested in the normal way, it is returned exactly as it was.


ascending

The id reference field is returned to the client in ascending order.

http://localhost:3000/comments?_sort=id or http://localhost:3000/comments?_sort=id&_order=ascCopy the code

The results are sorted in ascending order with the ID as the reference field.

In normal ascending order, _order=asc can not be passed. Just specify the reference field (_sort).


Descending order

The descending order must be _order=desc.

http://localhost:3000/comments?_sort=id&_order=desc
Copy the code


Multifield sort

The requirements this time are:

  1. First, they are arranged in ascending postId order

  2. Order the ids in reverse order on the basis of 1


Multiple fields are used, divided into compartments.

http://localhost:3000/comments?_sort=postId,id&_order=asc,desc
Copy the code


Return result:

{
  "comments": [
    { "id": 12, "body": "some comment 11", "postId": 1 },
    { "id": 11, "body": "some comment 1", "postId": 1 },
    { "id": 8, "body": "some comment 8", "postId": 1 },
    { "id": 7, "body": "some comment 5", "postId": 1 },
    { "id": 2, "body": "some comment 2", "postId": 1 },
    { "id": 9, "body": "some comment 9", "postId": 2 },
    { "id": 4, "body": "some comment 10", "postId": 2 },
    { "id": 3, "body": "some comment 3", "postId": 2 },
    { "id": 10, "body": "some comment 4", "postId": 3 },
    { "id": 6, "body": "some comment 6", "postId": 3 },
    { "id": 5, "body": "some comment 7", "postId": 3 },
    { "id": 1, "body": "some comment 11", "postId": 3 }
  ]
}
Copy the code

Meet the requirements.





Slice the query

Slicing means specifying head and tail; You can also specify the header and fragment length.

The keywords used are:

  • _start: Starting position (subscript, starting from 0)
  • _end: End position
  • _limit: Segment length


The total is going to be in headers.


Take this data for example

{
  "comments": [
    { "id": 1, "body": "some comment 1", "postId": 1 },
    { "id": 2, "body": "some comment 2", "postId": 1 },
    { "id": 3, "body": "some comment 3", "postId": 2 },
    { "id": 4, "body": "some comment 4", "postId": 3 },
    { "id": 5, "body": "some comment 5", "postId": 1 },
    { "id": 6, "body": "some comment 6", "postId": 3 },
    { "id": 7, "body": "some comment 7", "postId": 3 },
    { "id": 8, "body": "some comment 8", "postId": 1 },
    { "id": 9, "body": "some comment 9", "postId": 2 },
    { "id": 10, "body": "some comment 10", "postId": 2 },
    { "id": 11, "body": "some comment 11", "postId": 3 },
    { "id": 12, "body": "some comment 11", "postId": 1 }
  ]
}
Copy the code


Requirement: Return data with subscripts from 2-6


Use _start and _end

http://localhost:3000/comments?_start=2&_end=6
Copy the code


Use _start and _limit

http://localhost:3000/comments?_start=2&_limit=4
Copy the code





Range queries

Range query can be greater than or equal to, less than or equal to, or not equal to.


Greater than or equal to _get

The greater than or equal keyword is _get. Notice, there’s an underscore in front.

Requirement: Query data with id greater than or equal to 4 on the Comments interface

http://localhost:3000/comments?id_gte=4
Copy the code


Less than or equal to _LTE

Requirement: Query data whose ID is less than or equal to 4

http://localhost:3000/comments?id_lte=4
Copy the code


Combined use

Requirement: Query data whose ID is greater than or equal to 4 and less than or equal to 6 on the Comments interface

http://localhost:3000/comments?id_gte=4&id_lte=6
Copy the code


Is not equal to _ne

Requirement: Query data where id of comments interface is not equal to 2

http://localhost:3000/comments?id_ne=2
Copy the code





Fuzzy query

The keyword of fuzzy query is _like.

Requirement: Query the data of the Comments interface body containing 1





The full text query

The keyword of full-text query is Q

Prepare the following data for a good demonstration

{
  "authors": [{"id": 1."name": "zhangsan"."age": 18},
    { "id": 2."name": "lisi"."age": 21},
    { "id": 3."name": "wangwu"."age": 24}}]Copy the code


Query all columns containing 2

http://localhost:3000/authors?q=2
Copy the code

Because age is 24 in the data with id 3, it also contains 2.





Foreign key association query

Two interfaces are required for the foreign key query.

Prepare the following data for demonstration

{
  "posts": [{"id": 1."title": Article 111 ""."author": "Zhang" },
    { "id": 2."title": Article 222 ""."author": "Bill"}]."comments": [{"id": 1."body": "some comment 1"."postId": 1 },
    { "id": 2."body": "some comment 2"."postId": 1 },
    { "id": 3."body": "some comment 3"."postId": 2}}]Copy the code

There are two pieces of data in posts.

There are 3 pieces of data in comments, and each piece of data has a postId, which is the ID of each piece of data corresponding to posts.


Select * from comments where id = 1

http://localhost:3000/posts/1/comments
Copy the code





Relationship between assembled

Relational assembly can concatenate and return data from two associated interfaces.

There are two query relationships:

  • Include subresources_embed
  • Include parent resource_expand


Prepare the following data for demonstration

{
  "posts": [{"id": 1."title": Article 111 ""."author": "Zhang" },
    { "id": 2."title": Article 222 ""."author": "Bill"}]."comments": [{"id": 1."body": "some comment 1"."postId": 1 },
    { "id": 2."body": "some comment 2"."postId": 1 },
    { "id": 3."body": "some comment 3"."postId": 2}}]Copy the code


Contains the sub-resource _embed

http://localhost:3000/posts?_embed=comments
Copy the code


You can also concatenate multiple conditions.

Requirement: In comments, find and concatenate data from posts with ID 2

http://localhost:3000/posts/2?_embed=comments
Copy the code


Contains the parent resource _expand

http://localhost:3000/comments?_expand=post
Copy the code





Configure the routing

Sometimes our API addresses may not be as simple as in all of the above cases, and we can use the custom route method to simulate this.

For example, simulate the following interface:

http://localhost:3000/api/users/1
Copy the code


The implementation steps are as follows:

  1. createroutes.jsonFile (may not be called that)
  2. Used when starting the service--routesparameter


1. Create routes.json and enter the following content.

{
  "/api/*": "/ $1"
}
Copy the code


2. Start the service

json-server db.json --routes routes.json
Copy the code


3, access,

http://localhost:3000/api/posts
Copy the code








Static resource

Static resources include HTML, CSS, JS, images, and videos.


configuration

There are two configuration modes:

  • The default configuration
  • Specify resource location


The default configuration

You need to create a public folder in the root directory to put files such as HTML.


Then go to http://localhost:3000/ in your browser

You can also add your own CSS and JS for design interaction.





Specify resource location

The default way for jSON-server to allocate static resources is to create a public folder in the root directory and put the static resources in it.

However, if you don’t want to use public as the folder for static resources, you can also create a different name and use –static to specify the destination directory when you start the environment.


For example, if I create a some-other-dir directory for static resources, use the following command to specify the following.

json-server db.json --static ./some-other-dir
Copy the code





Multimedia resources

In addition to HTML, CSS and JS resources, you can also play images and videos.

I’ll take an image as an example. I’ll add an image under the public directory.


Simply follow the file name of the image at http://localhost:3000/.





other

Generating dynamic data

Creating a JSON file and typing it one by one is really out of date if we’re trying to emulate 100 or more pieces of data.

At this point we can use JS through a loop to achieve data creation.


1. Create a db.js file in the root directory.

2. Enter the content

module.exports = () = > {
  const data = { users: []}// Create 100 users
  for (let i = 0; i < 100; i++) {
    data.users.push({ id: i, name: `user${i}`})}return data
}
Copy the code


3. Run the JS file

json-server db.js
Copy the code


4. Look it up

 http://localhost:3000/users
Copy the code


100 pieces of data are generated directly.

What fields you need can be configured in the JS file.





Query the entire database

Access the following addresses to obtain data for the entire database.

 http://localhost:3000/db
Copy the code





Remote mode

If you want to use data from the Internet, you can simply run jSON-server and add the remote address.

json-server http://jsonplaceholder.typicode.com/db
Copy the code













If this article can help you, please give me a thumbs up