Network communication in wechat applet can only communicate with the designated domain name. Wechat applet includes four types of network requests.

  • Common HTTPS request (wx.request)
  • UploadFile (wx.uploadFile)
  • Download the file (wx.downloadfile)
  • WebSocket communication (wx connectSocket)

Here to introduce wx. Request, wx. UploadFile, wx. DowloadFile three network requests

Set the domain name

To communicate with wechat applets, you must first set the domain name, otherwise there will be an error:

The URL domain name is invalid. Please configure it in the MP background and try again

The domain name needs to be set in the mini program of wechat public platform. Setting options can be seen in the setting interface of wechat mini program:




Select development Settings:




The development set

You can see the server Settings:




Server Settings

Here you can set corresponding to the domain of four kinds of network access request each type of network you need to set up a domain name, note if here set the domain name to https://example.com/api/, https://example.com/api is unable to call, must add behind /.

The HTTP request

One HTTP request can be made using wx. Request, and a wechat applet is limited to only five web requests at the same time.

function queryRequest(data){    
    wx.request({
        url:"https://example.com/api/",
        data:data,
        header:{
           // "Content-Type":"application/json"
        },
        success:function(res){
            console.log(res.data)
        },
        fail:function(err){
            console.log(err)
        }

    })

}Copy the code

The code above sends an HTTP GET request and prints out the returned result. The parameters are easy to understand.

  • urlThe URL of the server
  • dataThe request argument can take a Stringdata:"xxx=xxx&xxx=xxx"Or Objectdata:{"userId":1}In the form of
  • headerSet the header for the request
  • successSuccessful callback of the interface. Procedure
  • failFailed callback of the interface. Procedure

There are two more parameters that are not in the code:

  • methodHTTP method, default is GET request
  • completeA callback after an interface is called that will be invoked regardless of success or failure

Upload a file

The API for uploading files is wx.uploadFile, which makes an HTTP POST request with a content-type of multipart/form-data. The server needs to receive a file of type content-type. Example code:

function uploadFile(file,data) {
    wx.uploadFile({
        url: 'http://example.com/upload',
        filePath: file,
        name: 'file',
        formData:data,
        success:function(res){
            console.log(res.data)
        },
        fail:function(err){
            console.log(err)
        }

    })

}Copy the code

The URLS, headers, Success, Fail, and complete are the same as normal HTTP requests. The different parameters are:

  • nameThe server must pass the key corresponding to the filenameParameter acquisition file
  • formDataAdditional parameters that can be used in HTTP requests

The download file

DownloadFile. This API initiates an HTTP get request and returns a temporary path to the file after a successful download. Example code:

function downloadFile(url,typ,success){
    wx.downloadFile({
        url:url,
        type:typ,
        success:function(res){
            if(success){
                success(res.tempFilePath)
            }
        },
        fail:function(err){
            console.log(err)
        }
    })
}Copy the code

The parameters of URL,header,fail,complete and wx.uploadFile are the same, and the differences are as follows:

  • type: Type of the downloaded resource, used for automatic identification by the client, available parametersimage/audio/video
  • Success: a callback after a successful download that returns the temporary directory of the file with tempFilePath: Res ={tempFilePath:’ file path ‘} This file is temporary and can only be used during the running of the program. If you want to persist the file, you need to call wx.saveFile to persist the file. Example code:

    function svaeFile(tempFile,success){
      wx.saveFile({
          tempFilePath:tempFile,
          success:function(res){
              var svaedFile=res.savedFilePath
              if(success){
                  success(svaeFile)
              }
          }
      })
    }Copy the code

    Use wx.saveFile to save a temporary file to the local computer for the next startup of the applet.

  • TempFilePath Specifies the path of the file to be saved

  • successSave the successful callback, return to the saved path, useres.savedFilePathYou can obtain the saved path
  • failFailed callback
  • completeClosed callback

Setting timeout

MINA has mentioned that setting networkTimeout in app.js can set the timeout time for four types of network access:

"networkTimeout":{
   "request": 10000,
   "connectSocket": 10000,
   "uploadFile": 10000,
   "downloadFile": 10000
}Copy the code

The timeout set here corresponds to four types of network requests.

Please refer to the source code: github.com/jjz/weixin-…