Home > WeChat Applet > Mini Program Development > WeChat applet development: http request

WeChat applet development: http request

高洛峰
Release: 2017-02-16 10:07:31
Original
1689 people have browsed it

Network communication in the WeChat applet can only communicate with the specified domain name. The WeChat applet includes four types of network requests.

  • Normal HTTPS request (wx.request)

  • Upload file (wx.uploadFile)

  • Download file (wx.downloadFile)

  • WebSocket communication (wx.connectSocket)

Here to introduce wx.request,wx.uploadFile,wx.dowloadFileThree types of network requests are the main ones

Set the domain name

If you want the WeChat applet to communicate over the network, you must Set the domain name first, otherwise an error will occur:

The URL domain name is illegal, please try again after mp background configuration

Needs to be set in the mini program of the WeChat public platform domain name.
You can see the setting options in the setting interface of the WeChat applet:

WeChat applet development: http request

Settings

SelectDevelopment Settings :

WeChat applet development: http request

Development settings


You can see the server settings:

WeChat applet development: http request

Server Settings


Here you can set the domain names corresponding to four types of network access. Each type of network request needs to set a domain name. Note that if you set the domain name https://example here .com/api/, then https://example.com/api cannot be called, and must be followed by /.

http request

Use wx.request to initiate an http request. A WeChat applet is limited to only 5 network 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 after login

The above code will send an http get request and then print out the returned results. The parameters are also relatively easy to understand.

  • url The url address of the server

  • data The request parameters can be String data:"xxx=xxx&xxx=xxx" or Object data:{"userId":1}

  • header Set the request header

  • success Interface success callback

  • fail Interface Failed callback

There are also two parameters not in the code:

  • method http method, default For GET request

  • complete The callback after calling the interface will be called regardless of success or failure

Upload files

The api for uploading files is wx.uploadFile, which will initiate a http post request, in which the Content-type is multipart/form-data. The server needs to receive files according to the Content-type 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 after login

among which url, header, success , fail and complete are the same as ordinary http requests. (WeChat applet application number exchange group 563752274)
The different parameters here are:

  • nameThe key corresponding to the file, the server needs to pass nameParameters to get the file

  • formData Other parameters that can be used in the http request

Download file

The api for downloading files is wx.downloadFile. This api will initiate an http get request and return the temporary path of the file after the download is successful. Sample 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 after login

The parameters of url, header, fail, complete and wx.uploadFile are consistent. The different parameters are:

  • type: The type of the downloaded resource, which is used for automatic identification by the client. Parameters that can be used image/audio/ video

  • success: Callback after successful download, returns the temporary directory of the file with the tempFilePath parameter: res ={tempFilePath:'File path'}
    After successful download, it is a temporary file, which can only be used during the current running of the program. If you need to save it permanently, you need to call the method wx.saveFile Actively persist files, example code:

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

    Use wx.saveFile to save temporary files locally and provide them for use when the applet is started next time. Parameters:

  • tempFilePath 需要被保存文件的路径

  • success 保存成功的回调,返回保存成功的路径,使用res.savedFilePath可以获取保存成功的路径

  • fail 失败的回调

  • complete结束的回调

超时的设置

在微信小程序开发:MINA中已经提到了在app.js中设置networkTimeout可以设置四种类型网络访问的超时时间:

"networkTimeout":{   
"request": 10000,   
"connectSocket": 10000,   
"uploadFile": 10000,   
"downloadFile": 10000
}
Copy after login

这里设置的超时时间对应着四种类型的网络请求。

更多WeChat applet development: http request相关文章请关注PHP中文网!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template