May 22, 2021 Mini Program Cloud Development Study Guide
Data and files are very important elements in the development of small programs, in the previous sections, data and files, etc. are stored in the pages of small programs for rendering, or between pages or interacting with local mobile phones. In this section, we'll talk about data, how files talk to network HTTP, how to get and upload network data and files.
The APIs for small programs and many programs are pre-written functions so that we don't need to know much about the underlying, we just need to pass parameters according to the technical documentation to invoke very complex functions. There's another kind of API that focuses on opening up data resources that we can use over HTTP.
Copy the following link address and open it with your browser to see what results will be returned:
//知乎日报的最新话题
https://news-at.zhihu.com/api/4/news/latest
//知乎日报某一个话题的内容
https://news-at.zhihu.com/api/4/news/9714883
//v2ex论坛的最新主题
https://www.v2ex.com/api/topics/latest.json
//CNode论坛的最新话题
https://cnodejs.org/api/v1/topics
The data types returned above are in json format, and I believe you should be familiar with them. So how do we render the above data on our small program page?
Data is a kind of resource, such as news information, e-commerce commodities, public articles, stock market, air quality and weather, maps, dictionary translation, express information, book information, music video, financial company information and so on these are data, data is also a commodity, a service, usually its use object is developers, some free, some will charge a certain fee, we can through the integrated API service platform aggregate API to have a basic understanding of API services.
Here are a few API resources that programmers often use to practice, which you can use for websites, applets, mobile (iOS, Android), desktop, or for various frameworks such as Vue, React, Flutter, and so on.
Major companies' development platforms: for example, WeChat Open Platform provides access to WeChat account system, Tencent Cloud API Center provides the ability to invoke cloud resources (including servers, Internet of Things, artificial intelligence and other APIs), open source website Wordpress also provides API call services, in the opening of API resources, foreign countries also do a relatively leading (foreign free API list). For specific data resources, it can also come from the building through reptiles and so on.
To render the data we get from the API, we first need to have a certain understanding of what the fields (attributes) in the API really do.
For example, the API field of the Daily News is as follows, which can be learned from the API-related
Console.log
console to understand.
Like what
date
: date;
stories
: News of the day;
title
News headlines;
images
image address;
id
:
url
share_url
last number in the message is the
id
top_stories
display of the rotation at the top of the interface.
This needs to be understood before data rendering can be done.
Use the developer tool to create a
request
page and enter the following
request.js
onLoad
in the request tool:
onLoad: function (options) {
wx.request({
url: 'https://news-at.zhihu.com/api/4/news/latest', //知乎日报最新话题
header: {
'content-type': 'application/json' // 默认值
},
success(res) {
console.log('网络请求成功之后获取到的数据',res)
console.log('知乎日报最新话题',res.data)
}
})
},
After compiling, you'll see in console Console that your domain name isn't on the domain whitelist because the program can only communicate with the specified domain name over the network.
request:fail url not in domain list
There are two solutions, one is to open the developer toolbar in the upper right corner of the details, check not to verify the legitimate domain name, business domain name, TLS version and HTTPS certificate;
After compilation, you can see the printed res object in the console Console, as well as the data object in the res.
res.data
data is exactly the json data we get when we
json
browser, and combined with what we've learned before about data rendering, I'm sure you shouldn't be unfamiliar with how to render the data to a page.
What do you mean by printing res objects such
cookies
header
statusCode
We can combine technical documentation to gain insight.
Technical documentation: wx.request network data request
statusCode
The HTTP status code returned by the developer server, which indicates whether the HTTP request was successful, of which 200 were successful, 404 requests failed, and more knowledge of the status code can be found in the MDN HTTP response code
header
The HTTP header returned by the developer server, where
Content-Type
is the MIME type of the server document and the MIME type of the API is
application/json; charset=UTF-8
recommends that the server return value be encoded with UTF-8 if you have a server.
wx.request
only initiate HTTPS requests, with a default timeout
60s
and a maximum 10 sympound limits
Small tasks: Swap
request
link for v2ex, the API link for the cnode forum, and the content API that knows a topic in the daily newspaper to see what the results are? Do you know what each attribute of the returned json data represents?
Now that we've got the data from the Knowledge Daily API, we've seen how to render the data and how to do cross-page rendering, as we learned earlier in the section.
Enter the list style
request.wxml
weui
developer tool (weui framework
weui
introduced)
<view class="page__bd">
<view class="weui-panel weui-panel_access">
<view class="weui-panel__bd" wx:for="{{stories}}" wx:for-item="stories" wx:key="*item">
<navigator url="" class="weui-media-box weui-media-box_appmsg" hover-class="weui-cell_active">
<view class="weui-media-box__hd weui-media-box__hd_in-appmsg">
<image class="weui-media-box__thumb" mode="widthFix" src="{{stories.images[0]}}" sytle="height:auto"></image>
</view>
<view class="weui-media-box__bd weui-media-box__bd_in-appmsg">
<view class="weui-media-box__title">{{stories.title}}</view>
</view>
</navigator>
</view>
</view>
</view>
Then declare
request.js
data
top_stories in the data of the
date
top_stories
(use variables and API fields as consistent as
stories
so that they are not easily confusing)
data: {
date:"",
stories:[],
top_stories:[],
},
In the onLoad lifecycle function, the data is assigned to data by setData:
onLoad: function (options) {
let that=this
wx.request({
url: 'https://news-at.zhihu.com/api/4/news/latest',
header: {
'content-type': 'application/json'
},
success(res) {
let date=res.data.date
let stories=res.data.stories
let top_stories = res.data.top_stories
that.setData({
date,stories,top_stories
})
}
})
},
After compiling, we can see that the data from the daily newspaper is rendered on the page.
Small tasks:
top_stories
the display of carnage at the top of the
top_stories
content from the top_stories to the carnage.
打开开发者工具调试工具栏的 AppData 标签页,就能看到从网络 API 里获取到的数据。也可以在此处编辑数据,并及时地反馈到界面上。如果 AppData 里有数据,可以确认页面已经取得 `res` 里的 `data` 数据,如果数据没有渲染到页面,说明列表渲染可能有误。通过这种方式可以诊断页面渲染问题所在。
What we've just obtained earlier is a list of the latest articles we know about. From the API documentation and the results of our link access, we only need to get the ID of the article to get the details page of the article from the API:
https://news-at.zhihu.com/api/4/news/9714883 //9714883是文章的ID
Use the developer tool to create a
story
page, and then enter the following code
story.wxml
<view class="page__bd">
<view class="weui-article">
<view class="weui-article__h1">{{title}}</view>
<view class="weui-article__section">
<view class="weui-article__section">
<view class="weui-article__p">
<image class="weui-article__img" src="{{image}}" mode="widthFix" style="width:100%" />
</view>
<view class="weui-article__p">
{{body}}
</view>
<view class="weui-article__p">
知乎链接:{{share_url}}
</view>
</view>
</view>
</view>
</view>
Then declare
request.js
data
title
image,
image
in the data
share_url
the request:
body
data: {
title:"",
body:"",
image:"",
share_url:"",
},
Call
wx.request
get the data from the article details page and assign the assignment to data via
setData
data
onLoad: function (options) {
let stories_id=9714883
let that = this
wx.request({
url: 'https://news-at.zhihu.com/api/4/news/'+stories_id,
header: {
'content-type': 'application/json'
},
success(res) {
let title = res.data.title
let body=res.data.body
let image=res.data.image
let share_url=res.data.share_url
that.setData({
title,body,image,share_url
})
}
})
After compilation, it is found that although the data is rendered out, but there is "garbled" (HTML tag), so how to deal with this? This involves rich text parsing of small programs.
Simply place the rich text object in the nodes of
rich-text
nodes
the rich text, for example, by replacing the above with the following code.
{{body}}
<rich-text nodes="{{body}}"></rich-text>
小程序富文本解析的方案还有:Comi ,腾讯 Omi 团队开发的小程序代码高亮和 markdown 渲染组件,Github 地址,具体效果可以在微信小程序里搜索 omiCloud;以及wxPrase,微信小程序富文本解析自定义组件,支持 HTML 及 markdown 解析,Github地址,当你遇到更加复杂的富文本解析时,可以来深入了解。
Above, we just rendered the details page of a single article, so how do you click on the list of articles to render the corresponding article details page? This goes back to the cross-page data rendering we learned earlier.
First place
request
page on the home page, and then bring the article's id to the link to the
navigator
component in
request.wxml
url="/pages/story/story?id={{stories.id}}"
When you
request
the link on the request page, the
story
that the link carries is
onLoad
options
the
options
the id in
id
stories_id
that
id 9714883
options.id
let stories_id=options.id
Then click on the link on the
request
page and the different links will render different article details.
Deconstructing assignments is the extraction of values from array arrays and object Objects, and assigning variables according to the position of the control. For example, the above variable declaration, in order to be able to correspond to the data fields in the API, we will declare a lot of variables, know the daily API is relatively small, more complex.
let title = res.data.title
let body=res.data.body
let image=res.data.image
let share_url=res.data.share_url
This can be simply written as:
let { title, body, image, share_url}=res.data
Knowing that the daily API is open and doesn't require us to sign up for the API service to get this data, but most of the time, the API is a commodity service and requires us to register, so what's the difference between the API that needs to be registered and the open API?
Sign up for aggregated APIs and certifications, after which you can apply for free API services such as today's history, book e-commerce data, and find your appKey.
Replace the key for today in your history (just lose AppKey directly) and open the link in your browser (here's version 1.0)
http://api.juheapi.com/japi/toh?month=9&day=15&key=你的历史上的今天对应的key
You can also select version 2.0 of the event list (for ease of explanation, the following is mainly version 1.0)
http://v.juhe.cn/todayOnhistory/queryEvent.php?date=9/15&key=你的历史上的今天对应的key
Usually we put the
key
we get in the
globalData
of
app.js
or create
config.js
small program for later global
key
directly on the page.
Method 1: Write
globalData
.js in the
app.js
application, or create
keyData
object, as long as the purpose of the global call
globalData
globalData: {
juheKey:"366444.......00ff", //聚合AppKey
},
This method is first called in the
js
the page, in front of the
Page()
function
const app=getApp()
You can then
app.globalData.juheKey
Method 2: You can also create a new
config.js
at the root of a small program or in the
utils
folder, and then write the following code in conjunction with the previous modular knowledge:
module.exports = {
juheKey:"366444.......00ff", //聚合AppKey
}
When we call this way, we need to introduce a modular file in front of the
Page()
function of the page
const key = require('../../utils/config.js')
You can then
key.juheKey
Taking out some common data and functions separately
globalData
or modularization is a method that is often used in real development to make data, functions easier to manage, and reusable, making the code more streamlined.
Use the developer tool to create a
apidata
page, and then enter the following code .js
Page()
apidata.js
tool:
const app=getApp()
const now = new Date();
const month = now.getMonth()+1 //月份需要+1
const day = now.getDate()
Then enter the wx.request data request in
wx.request
onLoad
onLoad: function (options) {
wx.request({
url: 'http://api.juheapi.com/japi/toh',
data: {
month: month,
day: day,
key: app.globalData.juheKey,
},
header: {
'content-type': 'application/json'
},
success(res) {
console.log(res.data)
}
})
},
wx.request
is the incoming parameter, and
month
data
day
key
into the requested link.
It is equivalent to the following link (note the property
data
in the data so as not to pass the parameters twice)
url: "http://api.juheapi.com/japi/toh?" + "month=" + month + "&day=" + day + "&key=" + app.globalData.juheKey,
To connect multiple strings, you can use the plus sign plus as a stitching of strings, wouldn't it be a hassle if there are more variables? W e can also use a template string, which is represented by an inverse quote '' (under the computer keyboard esc key). To embed a variable in a template string, you need to write the name of the variable in $, for example, the link above can also be written as:
url: `http://api.juheapi.com/japi/toh?month=${month}&day=${day}&key=${app.globalData.juheKey}`,
In the console we can see the
res.data
which is not much of a introduction to how to render to the page.
Sign
up for and windy
weather, and create a new app in the console's app management to get the
key
and add the
key
globalData
globalData: {
heweatherKey:"732c.........0b", //和风天气key
}
Technical documentation shows that the required fields for the free version and the Windy Weather API are
weather-type
(different data can be obtained depending on the value) and request
location
the required parameter)
Technical documentation: and wind regular weather data API
That is, we can get the data through the link,
now
before the question
?
is, it is not the requested parameter,
location
and
key
https://free-api.heweather.net/s6/weather/now?location=beijing&key=你的key
Then initialize the declaration
weathertype
(.js property names are best not to have
data
and
location
in the data of
apidata.js Page()
:
data: {
weathertype:"now",
location:"beijing" //location的写法有很多种,具体可以参考技术文档
},
Then add a
wx.request
function (you can write multiple
wx.request
onLoad
const weathertype=this.data.weathertype
wx.request({
url: `https://free-api.heweather.net/s6/weather/${weathertype}`,
data: {
location: that.data.location,
key: app.globalData.heweatherKey,
},
header: {
'content-type': 'application/json'
},
success(res) {
console.log(res.data)
}
})
},
You can see the requested
res.data
console.
If you want to click the button to switch between different cities and different weather data types, combined with what you learned
setData
through the event
weathertype
location
When browsing the web, we often see Chinese characters or some characters become a "garbled code", the reason is that the link is encoded.
encodeURI()
function encodes
URI
as URIs, while
decodeURI()
function decodes them.
Enter the following code in the console of the developer tool
console.log(encodeURI("北京"))
console.log(decodeURI("%e9%85%92%e5%ba%97"))
console.log(decodeURI("https://hackwork.org/handbook/python/174/%e5%86%99%e5%87%ba%e7%ac%ac%e4%b8%80%e8%a1%8cpython%e4%bb%a3%e7%a0%81/"))
If you want to call the MAP's POI retrieval (POI, or
Point of Interest
ATMs, etc.), keyword input tips, address resolution, reverse address resolution, administrative division, distance calculation, path planning, and other data services in a small program, you need to use the map class-related APIs.
Map API: Tencent LBS Location Service
First log in after registration, click on the console - key management - create a new key, and then get key, key in a format similar to "43UBZ- - HTBIA". -
Then click on the current Key settings, start the product to check the WeChat program and the signature verification in the WebService API, to get the map of The Secret Key. Both APIs are called in a way that is supported by small programs.
Then write the two keys of the map to
globalData
globalData: {
mapKey:"43UBZ-*****-IITUH-*****-2M723-******",//你的key
mapSecretKey:"spZwWz**********Xh20uW", //你的Secret key
}
In
the WebService API Key configuration, the
signature check mentions that our approach to
WebServiceAPI
requires a request path of
?
T
he request parameter,
SK
stitched and the
md5
the string after stitching is calculated, i.e. the signature (sig).
MD5
a widely used encryption algorithm in the field of computer security, which is mainly used to ensure the integrity and consistent transmission of messages.
After unziwing, copy and
md5.min.js
the js folder under the small program utils folder.
Then introduce
Page()
front of Page().
const md5 = require('../../utils/md5.min.js')
The inverse resolution of coordinates is
latitude
longitude
are converted into detailed address names.
Technical documentation: Inverse address parsing of coordinates
Then
apidata.js Page()
latitude
for example, we use the longitude and latitude values of the Tencent Building:
longitude
data: {
latitude:"22.540503",
longitude: "113.934528",
},
The HTTPS network request is then initiated
wx.request
in the onLoad function
onLoad: function (options) {
let that=this
const { latitude, longitude } = that.data
const { mapKey, mapSecretKey}=app.globalData
let SIG = md5("/ws/geocoder/v1?key=" + mapKey + "&location=" + latitude + "," + longitude + mapSecretKey)
wx.request({
url: 'https://apis.map.qq.com/ws/geocoder/v1',
data: {
key: mapKey,
location: `${latitude},${longitude}`,
sig: SIG
},
header: {
'content-type': 'application/json'
},
success(res) {
console.log(res.data)
}
})
},
In the console Console, you can see the
latitude
longitude
inversely resolved.
Small programs use Tencent map location services, and there is an easier way to read WeChat Small Programs: A Guide to Using Personality Maps