Construction and simple operation of JSON server environment for wechat applet

Learning video: https://www.bilibili.com/video/BV1Gv411g7j6?p=81

Template

Mainly selected articles
app. The path is written in JSON

Define template
In index Copy the following from wxml to articletemplate In wxml, the static content is modified to dynamic

<!--Selected article list structure template-->
<!-- Change static text to dynamic -->
<template name="articleTemplate">
  <view class="articleView">
    <view>
      <image src="{{imgUrls}}"></image>
    </view>
    <view class="articleContent">
      <view class="artivcleTitle">{{title}}</view>
      <view class="articleDesc">{{desc}}</view>
    </view>
  </view>
</template>

Then go to index Copy the style that implements it in wxss to articletemplate In wxss

/* Selected article list structure template style */
.articleView{
  display: flex;
  padding: 30rpx 0;
  border-bottom: 1rpx solid #F1EEF5;
}
.articleView image{
  width: 120rpx;
  height: 120rpx;
  margin-right: 20rpx;
}
.articleTitle{
  font-size: 28rpx;
  font-weight: bold;
  line-height: 50rpx;
}
.articleDesc{
  font-size: 26rpx;
  color: #B7B7B7;
  line-height: 35rpx;
}

Use template
1. In index Import is used to import the articleTemplate template in wxml. Import can use the template defined by the target file in this file.

2. In index Use @ import in wxss to import the styles required by the template

3. In index Use the is attribute in wxml to declare the required template, and then in index JS to pass in the data required by the template
index.wxml

<!-- Selected articles -->
<!-- Import template -->
<import src="/pages/template/articleTemplate/articleTemplate.wxml"></import>
<view id="hotArticleView">
  <view id="hotArticleTitleView">Selected articles</view>  <!-- Article title -->
  <!-- Use template -->
  <block wx:for="{{articelArray}}" wx:for-item="article" wx:key="*this">
    <template is="articleTemplate" data="{{...article}}"></template>
  </block>
  <!-- See more -->
  <!-- add to tab event tab Event: leave immediately after finger touch, similar to mouse click event -->
  <view id="moreView" bindtap="gofeaturedArticles">
    <text>See more</text>
    <view class="arrow"></view>
  </view>
</view>

index.js

 data: { 
    // The data in the template should match the data in the template
    articelArray:[
      {
      id:1000000,
      imgUrls:"/Images/article01.png",
      title:"It's beautiful that you live like yourself",
      desc:"For thousands of years, the ancients always connected people's character with natural things, and compared people's spiritual sentiment with the character of flowers, plants and trees."
    },
    {
      id:10000001,
      imgUrls:"/Images/article02.png",
      title:"This redemption is due to campus bullying",
      desc:"After your name, there is a phenomenal animation film in Japan---<The form of sound"
    },
    {
      id:10000002,
      imgUrls:"/Images/article03.png",
      title:"Depression and depression",
      desc:"Depression is a common mental disease, mainly manifested as depression, reduced interest, pessimism and slow thinking"
    }]
  },

The effect remains unchanged:

Then the following code can be deleted, and the template realizes code reuse.
In index Wxml delete these codes

Go to index Delete these styles from wxss:

Environment construction of JSON server

First, set up the node JS environment
Download: http://nodejs.cn/download/

install
After downloading, double-click the installation package and keep clicking next. You don't need to modify anything, but you'd better modify the default installation path.
After installation, the environment variables will be configured directly for you. You can go to the computer - > properties - > advanced system settings (full screen) - > view

You can also enter cmd in window+R to open the command manager, enter node -v to view the node version and npm -v to view the npm version

npm: Node Package Manager, which is based on node JS package manager, which is also the entire node The package manager with the most popular and supported third-party modules in the JS community
Original intention: it's easier for JavaScript developers to share and reuse code.
Upgrade npm version: npm install npm -g
Use the Taobao image command: npm install -g cnpm – registry=https://registry.npm.taobao.org
json-server
A server that runs locally on the front end and can store json data
In short, it is to simulate the interface data of the service end. It is generally used after the front and back ends are separated. The front-end personnel can build a JSON service locally without relying on API development and generate test data by themselves
json server is a server that stores json data
Installation:
Using npm global installation: npm install - G JSON server
Press Ctrl+C to interrupt exit
Check the version number to test whether the installation is successful: JSON server - V

Create json data (db.json)
Since you are creating data, you need to create a json data
Create a folder called fetch in any directory

Enter the folder, open the command line,

Execute the command: JSON server -- watch dB json

You can see that there is an additional dB in the directory JSON file

Open it to see some information generated by default.
/db is the whole db JSON package, and / posts, / comment, / profile are db Sub objects in JSON
JSON server dB Each key of the JSON root node is used as a router (route: path). Test data can be written according to this rule
So is the access address http://localhost:3000

Modify port number
You can specify your own port: JSON server – watch dB json –port 3001
After modifying the port number, if you think the start service command is long, you can start it in dB Create a new package. JSP under the JSON statistics file JSON file, configure the following information

Then directly start: npm run mock.

JSON server query (get) data

Copy the following code to DB JSON, delete the previous

{
  "fruits": [
      {
        "id": 1,
        "name": "Apple",//Garbled code in writing Chinese
        "price": 1.28
      },
      {
        "id": 2,
        "name": "banana", 
        "price": 3.88
      },
      {
        "id": 3,
        "name": "watermelon",
        "price": 1.98
      }
  ],
  "users": [
      {
        "name": {
          "username":"admin",
          "nickname":"changan"
        },
        "pwd": "123456"
      }
  ]
}

After the change, restart and find that there will be garbled code when writing Chinese

So change it to English and restart it
Get the fruit with id=3: http://localhost:3000/fruits/3 This method gets an object. This method is recommended

Another way is to get an array: http://localhost:3000/fruits?id=3

Multi criteria query: http://localhost:3000/fruits?name=banana&price=3.88

In dB Add a member to JSON and restart

"users": [
    {
      "name": {
        "username": "admin",
        "nickname": "changan"
      },
      "pwd": "123456"
    },
    {
        "name": {
          "username":"fengling",
          "nickname":"guangdong"
        },
        "pwd": "123456"
      }
  ]

Query the user nicknamed Guangdong: http://localhost:3000/users?name.nickname=guangdong

Paginate: http://localhost:3000/fruits?_page=1&_limit=3
db.json

{
  "fruits": [
    {
      "id": 1,
      "name": "Apple",
      "price": 1.28
    },
    {
      "id": 2,
      "name": "banana",
      "price": 3.88
    },
    {
      "id": 3,
      "name": "watermelon",
      "price": 1.98
    },
    {
      "id": 4,
      "name": "Apple1",
      "price": 8.28
    },
    {
      "id": 5,
      "name": "banana1",
      "price": 4.88
    },
    {
      "id": 6,
      "name": "watermelon1",
      "price": 3
    }
  ],
  "users": [
    {
      "name": {
        "username": "admin",
        "nickname": "changan"
      },
      "pwd": "123456"
    },
    {
      "name": {
        "username": "fengling",
        "nickname": "guangdong"
      },
      "pwd": "123456"
    }
  ]
}

Then restart JSON server. Sometimes you have to restart it, sometimes you don't

Sort: (asc: the default is | desc), and | order specifies forward and reverse sorting

http://localhost:3000/fruits?_sort=id&_order=desc 


Take only the first data after sorting:

http://localhost:3000/fruits?_sort=id&_order=desc&limit=3 

Local data Slice
Slice mode and array Slice () method is similar. Adopt_ Start to specify the start position; Use_ limit to set how many data to get back from the starting position.

http://localhost:3000/fruits?_start=2&_end=5 

Take operators that meet a certain range
(1) Use _gte _lte to set a value range
For ID > = 2 and ID < = 4: http://localhost:3000/fruits?id_gte=2&id_lte=4

(2) Use _neto set not to contain a value (_ne: not equal to)
Excluding id=3: http://localhost:3000/fruits?id_ne=3 ;
You can also write more: http://localhost:3000/fruits?id_ne=3&id_ne=4&id_ne=6

(3) Use _like to match a string (or regular expression)
Fuzzy query: http://localhost:3000/fruits?name_like=b

Full text search
Use q to set the search content
This is similar to fuzzy query.
q means full-text search, not name or other fields. As long as the search content is included, it will help you query and display it all:

http://localhost:3000/fruits?q=3

JSON server addition, deletion and modification

First create a new folder and then open it through the editing tool. My editing tool is Visual Studio Code

Then create a new folder and html in it and reference the jQuery file

fruit.html:

<!DOCTYPE html>
<html>
    <head>
        <title>use jquery ajax Method operation data</title>
        <!-- Remember to change your path -->
        <script type="text/javascript" src="js/jquery.min.js"></script>
        <style>
            table,
            td,
            th {
                border: 1px solid black;
                border-collapse: collapse;
            }
            table {
                width: 500px;
                text-align: center;
            }
            tr {
                height: 35px;
            }
        </style>
    </head>
    <body>
        <button id="getBtn">Get all fruit data</button>
        <div id="showData"></div>
        <script type="text/javascript">
            $("#getBtn").click(function () {
                $.ajax({
                    type: 'get',
                    url: 'http://localhost:3000/fruits', / / remember to change it to your own port number
                    success: function (data) {
                        // data object array
                        var h = ""
                        h += "<table border='1'>"
                        h += "<thead><th>ID</th><th>name</th><th>price</th></thead>"
                        h += "<tbody>"
                        for (var i = 0; i < data.length; i++) {
                            var o = data[i]
                            h += "<tr>"
                            h += "<td>" + o.id + "</td><td>" + o.name + "</td><td>" + o.price + "</td>"
                            h += "</tr>"
                        }
                        h += "<tbody>"
                        h += "</table>"
                        $("#showData").empty().append(h)
                    },
                    error: function () {
                        alert("get : error")
                    }
                })
            })
        </script>
    </body>
</html>

Click Run

Then click the button to display the data

1, Add data
Post request, enter the new fruit name and price in the input box of the page, and add it to DB through post JSON.
In fruit Add this code to HTML
The name and price in the data should follow dB JSON. id does not need to be written. The id in JSON server is generated automatically
Go directly to the browser to view and add data

Then look at dB JSON, with the newly added data

2, Update data
put submission is often used to update existing resources. If the resources do not exist, they are created. Example: in dB JSON has a fruit with id=3, but if the price is changed in the input box, this data will be added, but there is no name field in this data.
In fruit HTML

In browser

Original dB JSON content

Because the put method will update the entire resource object, the fields not given in the front end will be cleared automatically.. So either we give the complete object in the data of ajax, or we use the patch method.
patch method is a new method, which can be said to be a supplement to put method. It is mainly used for local update
Change the type above to patch

Then the name field is still there, and the knowledge price changes, but this becomes a string type.

3, Delete data
Delete data by id
In fruit HTML

To delete the front data, you have to add the following code. Because I can't use it http://localhost:3000/fruits/ This request URL. You must specify the ID of the deleted object, which can only be deleted through the loop. Therefore, you need to obtain the current maximum ID through the get method as the loop boundary. For example: id=1, id=2, id=3. You need to obtain the maximum ID of id=3

Then go to the browser and operate it

Configure static resource server

This is mainly used to configure picture, audio and video resources
Configuring routing, data files, monitoring, etc. through the command line will make the command very long and easy to input errors;
JSON server allows us to put all the configurations into one configuration file, which is generally named json_server_config.json
json_server_config.json

{
  "port":3000,
  "watch":true,
  "static":"./public",//package folder of the current directory (static resource directory)
  "read-only":false,//Read only
  "no-cors":true,//Is cross domain supported
  "no-gzip":false
}

package.json

{
	"scrpits":{
		"mock":"json-server --c json_server_config.json db.json"
	}
}

We can put all our picture resources in the public directory, but the public directory can not only put pictures, but also audio and video. When putting resources, create images under public to place pictures, and create audio/video to place audio and video respectively;
Now that we're already in json_server_config.json indicates the directory of static files, so we can ignore public when accessing;
Copy the images in the images file to the new public folder

Then put it in public

For example, you want to access the QR code picture inside
Restart JSON server to access: http://localhost:3000/Images/@2x_2weima.png

You must learn the syntax of WXML before data interaction. (data binding, list rendering, conditional rendering, template)

Keywords: Mini Program

Added by peranha on Thu, 16 Dec 2021 04:34:38 +0200