Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Cloud Development Network API


May 22, 2021 Mini Program Cloud Development Study Guide


Table of contents


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.

Data API

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.

Learn about the network data API

Copy the following link address and open it with your browser to see what results will be returned:

  1. //知乎日报的最新话题
  2. https://news-at.zhihu.com/api/4/news/latest
  3. //知乎日报某一个话题的内容
  4. https://news-at.zhihu.com/api/4/news/9714883
  5. //v2ex论坛的最新主题
  6. https://www.v2ex.com/api/topics/latest.json
  7. //CNode论坛的最新话题
  8. 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.

Practice API resource recommendations

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.

Render network data to the page

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.

Get network data

Use the developer tool to create a request page and enter the following request.js onLoad in the request tool:

  1. onLoad: function (options) {
  2. wx.request({
  3. url: 'https://news-at.zhihu.com/api/4/news/latest', //知乎日报最新话题
  4. header: {
  5. 'content-type': 'application/json' // 默认值
  6. },
  7. success(res) {
  8. console.log('网络请求成功之后获取到的数据',res)
  9. console.log('知乎日报最新话题',res.data)
  10. }
  11. })
  12. },

Domain name check and whitelist

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.

  1. 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;

Res objects and res.data objects

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?

Render the data to the page

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.

Simple knowledge of the front page of the daily newspaper

Enter the list style request.wxml weui developer tool (weui framework weui introduced)

  1. <view class="page__bd">
  2. <view class="weui-panel weui-panel_access">
  3. <view class="weui-panel__bd" wx:for="{{stories}}" wx:for-item="stories" wx:key="*item">
  4. <navigator url="" class="weui-media-box weui-media-box_appmsg" hover-class="weui-cell_active">
  5. <view class="weui-media-box__hd weui-media-box__hd_in-appmsg">
  6. <image class="weui-media-box__thumb" mode="widthFix" src="{{stories.images[0]}}" sytle="height:auto"></image>
  7. </view>
  8. <view class="weui-media-box__bd weui-media-box__bd_in-appmsg">
  9. <view class="weui-media-box__title">{{stories.title}}</view>
  10. </view>
  11. </navigator>
  12. </view>
  13. </view>
  14. </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)

  1. data: {
  2. date:"",
  3. stories:[],
  4. top_stories:[],
  5. },

In the onLoad lifecycle function, the data is assigned to data by setData:

  1. onLoad: function (options) {
  2. let that=this
  3. wx.request({
  4. url: 'https://news-at.zhihu.com/api/4/news/latest',
  5. header: {
  6. 'content-type': 'application/json'
  7. },
  8. success(res) {
  9. let date=res.data.date
  10. let stories=res.data.stories
  11. let top_stories = res.data.top_stories
  12. that.setData({
  13. date,stories,top_stories
  14. })
  15. }
  16. })
  17. },

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.

  1. 打开开发者工具调试工具栏的 AppData 标签页,就能看到从网络 API 里获取到的数据。也可以在此处编辑数据,并及时地反馈到界面上。如果 AppData 里有数据,可以确认页面已经取得 `res` 里的 `data` 数据,如果数据没有渲染到页面,说明列表渲染可能有误。通过这种方式可以诊断页面渲染问题所在。

Details page data rendering

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:

  1. 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

  1. <view class="page__bd">
  2. <view class="weui-article">
  3. <view class="weui-article__h1">{{title}}</view>
  4. <view class="weui-article__section">
  5. <view class="weui-article__section">
  6. <view class="weui-article__p">
  7. <image class="weui-article__img" src="{{image}}" mode="widthFix" style="width:100%" />
  8. </view>
  9. <view class="weui-article__p">
  10. {{body}}
  11. </view>
  12. <view class="weui-article__p">
  13. 知乎链接:{{share_url}}
  14. </view>
  15. </view>
  16. </view>
  17. </view>
  18. </view>

Then declare request.js data title image, image in the data share_url the request: body

  1. data: {
  2. title:"",
  3. body:"",
  4. image:"",
  5. share_url:"",
  6. },

Call wx.request get the data from the article details page and assign the assignment to data via setData data

  1. onLoad: function (options) {
  2. let stories_id=9714883
  3. let that = this
  4. wx.request({
  5. url: 'https://news-at.zhihu.com/api/4/news/'+stories_id,
  6. header: {
  7. 'content-type': 'application/json'
  8. },
  9. success(res) {
  10. let title = res.data.title
  11. let body=res.data.body
  12. let image=res.data.image
  13. let share_url=res.data.share_url
  14. that.setData({
  15. title,body,image,share_url
  16. })
  17. }
  18. })

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.

HTML tag parsing rich-text

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}}

  1. <rich-text nodes="{{body}}"></rich-text>
  1. 小程序富文本解析的方案还有:Comi ,腾讯 Omi 团队开发的小程序代码高亮和 markdown 渲染组件,Github 地址,具体效果可以在微信小程序里搜索 omiCloud;以及wxPrase,微信小程序富文本解析自定义组件,支持 HTML markdown 解析,Github地址,当你遇到更加复杂的富文本解析时,可以来深入了解。

Cross-page data rendering

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

  1. 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

  1. let stories_id=options.id

Then click on the link on the request page and the different links will render different article details.

Deconstruct the assignment

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.

  1. let title = res.data.title
  2. let body=res.data.body
  3. let image=res.data.image
  4. let share_url=res.data.share_url

This can be simply written as:

  1. let { title, body, image, share_url}=res.data

Today in history

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 today's service in history

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)

  1. 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)

  1. http://v.juhe.cn/todayOnhistory/queryEvent.php?date=9/15&key=你的历史上的今天对应的key

Key storage

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

  1. globalData: {
  2. juheKey:"366444.......00ff", //聚合AppKey
  3. },

This method is first called in the js the page, in front of the Page() function

  1. 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:

  1. module.exports = {
  2. juheKey:"366444.......00ff", //聚合AppKey
  3. }

When we call this way, we need to introduce a modular file in front of the Page() function of the page

  1. 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.

wx.request request data

Use the developer tool to create a apidata page, and then enter the following code .js Page() apidata.js tool:

  1. const app=getApp()
  2. const now = new Date();
  3. const month = now.getMonth()+1 //月份需要+1
  4. const day = now.getDate()

Then enter the wx.request data request in wx.request onLoad

  1. onLoad: function (options) {
  2. wx.request({
  3. url: 'http://api.juheapi.com/japi/toh',
  4. data: {
  5. month: month,
  6. day: day,
  7. key: app.globalData.juheKey,
  8. },
  9. header: {
  10. 'content-type': 'application/json'
  11. },
  12. success(res) {
  13. console.log(res.data)
  14. }
  15. })
  16. },

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)

  1. url: "http://api.juheapi.com/japi/toh?" + "month=" + month + "&day=" + day + "&key=" + app.globalData.juheKey,

The template string

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:

  1. 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.

Weather API

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

  1. globalData: {
  2. heweatherKey:"732c.........0b", //和风天气key
  3. }

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

  1. 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() :

  1. data: {
  2. weathertype:"now",
  3. location:"beijing" //location的写法有很多种,具体可以参考技术文档
  4. },

Then add a wx.request function (you can write multiple wx.request onLoad

  1. const weathertype=this.data.weathertype
  2. wx.request({
  3. url: `https://free-api.heweather.net/s6/weather/${weathertype}`,
  4. data: {
  5. location: that.data.location,
  6. key: app.globalData.heweatherKey,
  7. },
  8. header: {
  9. 'content-type': 'application/json'
  10. },
  11. success(res) {
  12. console.log(res.data)
  13. }
  14. })
  15. },

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

encodeURI and decodeURI

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

  1. console.log(encodeURI("北京"))
  2. console.log(decodeURI("%e9%85%92%e5%ba%97"))
  3. 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/"))

Tencent Map LBS

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

Sign up for an account to get Key

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

  1. globalData: {
  2. mapKey:"43UBZ-*****-IITUH-*****-2M723-******",//你的key
  3. mapSecretKey:"spZwWz**********Xh20uW", //你的Secret key
  4. }

md5 encryption algorithm

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.

md5 dependency: md5 open source project download link

After unziwing, copy and md5.min.js the js folder under the small program utils folder. Then introduce Page() front of Page().

  1. const md5 = require('../../utils/md5.min.js')

Coordinate inverse resolution

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

  1. data: {
  2. latitude:"22.540503",
  3. longitude: "113.934528",
  4. },

The HTTPS network request is then initiated wx.request in the onLoad function

  1. onLoad: function (options) {
  2. let that=this
  3. const { latitude, longitude } = that.data
  4. const { mapKey, mapSecretKey}=app.globalData
  5. let SIG = md5("/ws/geocoder/v1?key=" + mapKey + "&location=" + latitude + "," + longitude + mapSecretKey)
  6. wx.request({
  7. url: 'https://apis.map.qq.com/ws/geocoder/v1',
  8. data: {
  9. key: mapKey,
  10. location: `${latitude},${longitude}`,
  11. sig: SIG
  12. },
  13. header: {
  14. 'content-type': 'application/json'
  15. },
  16. success(res) {
  17. console.log(res.data)
  18. }
  19. })
  20. },

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