All Products
Search
Document Center

Network

Last Updated: Apr 20, 2021

my.request

Network request of a Mini Program.

  • my.request currently supports GET/POST/PUT/DELETE.
  • my.request currently only supports HTTPS protocol requests.
Note:
  • This interface is supported since basic library version 1.1.0. my.canIUse('request') can be used for Compatibility processing for earlier versions. See Mini Program base library to learn more.
  • This API is supported in mPaaS 10.1.60 and later versions.
  • The interface my.httpRequest will be deprecated, please use my.request instead.
  • The default value of the request header of my.request is {'content-type':'application/json'}, not {'content-type':'application/x-www-form-urlencoded'}. In addition, the key and value in the request header object must be of String type.

For more information, see my.request FAQ.

Instructions for use:

  • You need to turn on the Permission control switch of the mini program in the figure below in Release Mini Program > Open Platform Mini Program Management in advance, and configure the domain name whitelist in the Server domain name whitelist. The mini program can only communicate with the domain names in the whitelist when calling the following APIs: HTTP request (my.request), upload file (my.uploadFile). whitelist
  • After adding the server domain name whitelist, you need to repackage and upload to generate the trial version, and the server domain name will take effect.
  • When debugging on the IDE, please use the real device to preview and debug.

Input parameter

Property Type Mandatory Description
url String Yes Target server url.
headers Object No Set the request HTTP header. The default value is {'content-type': 'application/json'}. The key and value in the object must be String.
method String No The default value is GET. GET/POST/PUT/DELETE are supported.
data Object No Data parameter description.
timeout Number No Timeout period, in ms. The default value is 30000.
dataType String No Expected format of the returned data. The following formats are supported:
json
text
base64
The default format is json.
success Function No Callback function for successful call.
fail Function No Callback function for failed call.
complete Function No Callback function for ended call (executed regardless of whether the call is successful or failed).

Data parameter description

Data transferred to the server is eventually expressed in String. If the type is not String, the data will be converted into String. Conversion rules are:

  • If the method is GET, the data will be converted into query string: encodeURIComponent(k)=encodeURIComponent(v)&encodeURIComponent(k)=encodeURIComponent(v)....
  • If the method is POST and the headers['content-type'] is application/json, the data will be JSON serialized.
  • If the method is POST and the headers['content-type'] is application/x-www-form-urlencoded, the data will be converted into query string: encodeURIComponent(k)=encodeURIComponent(v)&encodeURIComponent(k)=encodeURIComponent(v)....

referer description

-The referer header of the network request cannot be set.-The format is fixed to https://urlhost/{appid}/{version}/page-frame.html, where {appid} is the APPID of the mini program and {version} is the version number of the mini program.

Success Callback Function

Name Type Description
data String Response data. The format depends on the value of dataType in the request.
status Number Response code
headers Object Response header

Error code

Error code Description Solution
1 The request is not over, and it jumps to another page It is recommended that the page jump after the request is completed
2 Incorrect parameter.
  • It may be caused by the link being too long. It is recommended that the parameters be processed in data.
  • It is recommended to check whether the data passed in the request is normal and whether the format is correct. You can print the parameter data log before requesting.
11 No cross-domain permission Check whether the requested domain name is added to the domain name whitelist. For the development version test, click on the upper right corner of the IDE > Details, and check Ignore httpRequest domain name validity check.
Note: When a new version is online, you must add the Server domain name whitelist, otherwise an exception will occur.
12 Network error It is recommended to check whether the network environment is normal and whether the server is stable.
13 Timeout It is recommended to check whether the network environment is normal and whether the server responds normally. If the request takes a long time, the timeout period timeout can be set accordingly.
14 Decoding failed It is recommended to check whether the front-end and back-end request and response data formats are consistent. If the returned data format text is inconsistent with the input parameter dataType value JSON, which causes the interface to report an error, please modify the backend data format to be JSON.
15 Failed to transfer parameters. If you use urlencode to pass parameters on the mini program page, you need to encode the overall parameters.
19 HTTP error
  • Please confirm whether the request URL address can normally request the HTTPS protocol on the external network. The mini program requests in real devices are formal requests in the online environment and cannot use the local network request.
  • If you encounter HTTP 404, 500, 504 and other errors, it is recommended to open the IDE debugger > Network to view the specific error information, and then deal with it according to the corresponding HTTP error code.
  • The SSL certificate is incorrect. It is recommended to replace the website SSL certificate.
20 The request has been stopped / Traffic limited in server Please confirm whether the requesting server can request and respond normally.
23 The proxy request failed. It is recommended to check whether the proxy configuration is correct.

Note: When the value of the input parameter dataType is json, the applet framework will first perform the JSON.prase operation on the returned result. If the parsing fails, a code 14 error will be returned. When the input parameter dataType value is text, if the returned content format does not match, a code 14 error will also be returned. When encountering this error, please check whether the dataType setting is correct.

If the call to my.request returns that You are not authorized to call this interface, you need to configure the domain name whitelist in Open Platform Mini Program Management > Server domain name whitelist.

whitelist

Code sample

The code is for reference only, it is recommended to use your own address for testing.

  1. my.request({
  2. url: 'https://httpbin.org/post',
  3. method: 'POST',
  4. data: {
  5. from: 'Alipay',
  6. production: 'AlipayJSAPI',
  7. },
  8. dataType: 'json',
  9. success: function(res) {
  10. my.alert({content: 'success'});
  11. },
  12. fail: function(res) {
  13. my.alert({content: 'fail'});
  14. },
  15. complete: function(res) {
  16. my.hideLoading();
  17. my.alert({content: 'complete'});
  18. }
  19. });
  20. // Return RequestTask, you can call abort method to cancel the request
  21. const task = my.request({url: 'https://httpbin.org/post'})
  22. task.abort()

Return value

RequestTask

Network request task object.

Method

RequestTask.abort()

my.uploadFile

This API is supported in mPaaS 10.1.32 and later versions.

Upload local resources to the developer server.

Instructions for use:
You need to configure the domain name whitelist in Open Platform Mini Program Management > Server domain name whitelist in advance. The mini program can only communicate with the domain names in the whitelist when calling the following APIs: HTTP request (my.request), upload file (my.uploadFile).

whitelist

Input parameter

Name Type Required Description
url String Yes Developer server address
filePath String Yes Local locator of the file resources to be uploaded
fileName String Yes The file name, which is the corresponding key. The developer can obtain the binary content of the file through the key on the server.
fileType String Yes File type, which can be image, video or audio
header Object No HTTP request header
formData Object No Additional form data in the HTTP request
success Function No Callback function for successful call
fail Function No Callback function for failed call
complete Function No Callback function for ended call (executed regardless of whether the call is successful or failed)

success return value

Name Type Description
data String Data returned by the server
statusCode String HTTP status code
header Object The header returned by the server

Error Code

Error Code Description
11 File does not exist
12 File upload failed
13 No access

Code sample

  1. my.uploadFile({
  2. url: 'Please use your own server address',
  3. fileType: 'image',
  4. fileName: 'file',
  5. filePath: '...',
  6. success: (res) => {
  7. my.alert({
  8. content: 'Upload successful'
  9. });
  10. },
  11. });

UploadTask

Monitor the upload progress change and cancel the upload task object.

Method

Method Description
UploadTask.abort() Interrupt upload task
UploadTask.onProgressUpdate(function callback) Monitor upload progress change event

Code sample

  1. const task = my.uploadFile({
  2. url: 'Please use your own server address',
  3. fileType: 'image',
  4. fileName: 'file',
  5. filePath: '...',
  6. });
  7. task.onProgressUpdate(({progress, totalBytesWritten, totalBytesExpectedToWrite}) => {
  8. })
  9. task.abort()

FAQ

  • Q: Can images uploaded by the Mini Program be automatically converted to Base64 (based on 64 printable characters to represent binary data)?
    A: Currently, the mini program does not support the conversion of pictures to Base64.
  • Q: How can my.uploadFile obtain the error message returned by the server?
    A:
    • It can be obtained through the data parameter in the success callback.
    • A log acquisition interface can be added on the server side. If the upload fails, a request is made to the log acquisition interface to obtain detailed failure logs.
  • Q: What is the default timeout period of my.uploadFile? Can I extend the default time?
    A: The default timeout period of my.uploadFile is 30 s, and the default time cannot be set at present.
  • Q: I use my.uploadFile to upload files, why is there an error error:12?
    A: The upload failure results in the error error:12. The possible reasons for the upload failure are:
    • The file is too large.
    • The upload time exceeds 30s.
    • Permission denied.
  • Q: Use my.uploadFile to upload a picture to the back end. The binary picture is received, and then the binary picture is sent from the back end to the mini program foreground. How does the mini program foreground parse it?
    A: Uploading a picture means that the back end receives the picture through a binary stream, and then the back end only needs to provide the location address of the corresponding picture on the server.
  • Q: When calling my.uploadfile, why is there an error of error: 4, and I don’t have permission to call this interface?
    A: The requested URL is not configured with a whitelist. It is recommended to add the domain name of the URL to the whitelist.
  • Q: Does the Mini Program support uploading excel files?
    A: Currently the upload file type of my.uploadFile supports image, video, audio (image / video / audio), and other types of files are not currently supported.
  • Q: Does my.uploadFile support uploading multiple pictures at the same time?
    A: my.uploadFile does not support uploading multiple pictures at the same time. Only one picture can be uploaded at a time.

my.downloadFile

This API is supported in mPaaS 10.1.32 and later versions.

Download the file resource to local position.

Input parameter

Name Type Required Description
url String Yes Address of file downloaded
header Object No HTTP request header
success Function No Callback function for successful call
fail Function No Callback function for failed call
complete Function No Callback function for ended call (executed regardless of whether the call is successful or failed)

success return value

Name Type Description
apFilePath String Temporary storage location of files

Error code

Error code Description
12 Download failed
13 No access
20 The requested URL does not support HTTP It is recommended to change the requested URL to HTTPS

Code sample

The code is for reference only, it is recommended to use your own address for testing.

  1. // API-DEMO page/API/download-file/download-file.json
  2. {
  3. "defaultTitle": "Download file"
  4. }
  1. <!-- API-DEMO page/API/download-file/download-file.axml-->
  2. <view class="container">
  3. <button onTap="download">Download image and display</button>
  4. </view>
  1. // API-DEMO page/API/download-file/download-file.js
  2. Page({
  3. download() {
  4. my.downloadFile({
  5. url: 'https://img.alicdn.com/tfs/TB1x669SXXXXXbdaFXXXXXXXXXX-520-280.jpg',
  6. success({ apFilePath }) {
  7. my.previewImage({
  8. urls: [apFilePath],
  9. });
  10. },
  11. fail(res) {
  12. my.alert({
  13. content: res.errorMessage || res.error,
  14. });
  15. },
  16. });
  17. },
  18. })

my.connectSocket

This API is supported in mPaaS 10.1.60 and later versions.

Create a WebSocket connection.

A mPaaS mini program can only keep one WebSocket connection at a time. If a WebSocket connection already exists, it will be automatically closed, and then a new WebSocket connection will be re-created.

Input parameter

Name Type Required Description
url String Yes Target server URL. Note: Some newly released applets only support the wss protocol.
data Object No Parameters requested
header Object No Set request header
success Function No Callback function for successful call
fail Function No Callback function for failed call
complete Function No Callback function for ended call (executed regardless of whether the call is successful or failed)

Error code

Error code Description Solution
1 Unknown error -
2 The network connection already exists A mini program can only retain one WebSocket connection for a period of time. If there is already a WebSocket connection, it will be automatically closed and a new WebSocket connection will be created.
3 URL parameter is empty Replace URL link.
4 Unrecognized URL format Replace URL link.
5 URL must start with ws or wss Replace URL link.
6 Connection to server timed out Try again later.
7 The https certificate returned by the server is invalid The mini program must use HTTPS/WSS to initiate network requests. When requesting, the system will verify the HTTPS certificate used by the server domain name. If the verification fails, the request cannot be successfully initiated. Due to system limitations, different platforms have different stringent requirements for certificates. In order to ensure the compatibility of applets, it is recommended that developers configure certificates in accordance with the highest standards and use relevant tools to check existing certificates to ensure that they meet the requirements.
8 Invalid protocol header returned by the server For newly created mini programs starting in May 2019, the HTTPS and WSS protocols are mandatory by default, and the HTTP and WS protocols are no longer supported.
9 The Sec-WebSocket-Protocol request header not specified in WebSocket request Please specify the Sec-WebSocket-Protocol request header.
10 No network connection, and the message cannot be sent Please call my.sendSocketMessage to send data messages after connecting to the server normally. You can use my.onSocketOpen to monitor events. Determine the correct connection with the server.
Note: To send data through a WebSocket connection, you need to use my.connectSocket to initiate a connection, and then call my.onSocketOpen](#my.onSocketOpen) after the callback .sendSocketMessage Send data.
11 Message failed to send Try again later.
12 Cannot apply for more memory to read network data Please check the memory.

Code sample

The code is for reference only, it is recommended to use your own address for testing.

  1. my.connectSocket({
  2. url: 'test.php',
  3. data: {},
  4. header:{
  5. 'content-type': 'application/json'
  6. },
  7. });

my.onSocketOpen

This API is supported in mPaaS 10.1.60 and later versions.

Listen to the WebSocket connection establishment event.

Input parameter

Object type, the properties are as follows:

Attribute Type Required Description
callback Function Yes The callback function of the WebSocket connection open event.

Code sample

The code is for reference only, it is recommended to use your own address for testing.

  1. my.connectSocket({
  2. url: 'test.php',
  3. });
  4. my.onSocketOpen(function(res) {
  5. console.log('WebSocket connection is established! ');
  6. });

my.offSocketOpen

This API is supported in mPaaS 10.1.60 and later versions.

Cancel listening of WebSocket connection establishment event.

Code sample

The code is for reference only, it is recommended to use your own address for testing.

  1. Page({
  2. onLoad() {
  3. this.callback = this.callback.bind(this);
  4. my.onSocketOpen(this.callback);
  5. },
  6. onUnload() {
  7. my.offSocketOpen(this.callback);
  8. },
  9. callback(res) {
  10. },
  11. })

Whether to pass the callback value

  • If the callback value is not passed, all event callbacks will be removed. The code sample is as follows:
    1. my.offSocketOpen();
  • If the callback value is passed, only remove the corresponding callback event. The code sample is as follows:
    1. my.offSocketOpen(this.callback);

my.onSocketError

This API is supported in mPaaS 10.1.60 and later versions.

Listen to WebSocket errors.

Input parameter

Name Type Required Description
callback Function Yes The callback function of WebSocket error event.

Code sample

The code is for reference only, it is recommended to use your own address for testing.

  1. my.connectSocket({
  2. url: 'Developer server address'
  3. });
  4. my.onSocketOpen(function(res){
  5. console.log('WebSocket connection is established! ');
  6. });
  7. my.onSocketError(function(res){
  8. console.log('WebSocket connection failed to establish, please check! ');
  9. });

my.offSocketError

This API is supported in mPaaS 10.1.60 and later versions.

Cancel WebSocket listening error.

Code sample

The code is for reference only, it is recommended to use your own address for testing.

  1. Page({
  2. onLoad() {
  3. this.callback = this.callback.bind(this);
  4. my.onSocketError(this.callback);
  5. },
  6. onUnload() {
  7. my.offSocketError(this.callback);
  8. },
  9. callback(res) {
  10. },
  11. })

Whether to pass the callback value

  • If the callback value is not passed, all event callbacks will be removed. The code sample is as follows:
    1. my.offSocketError();
  • If the callback value is passed, only remove the corresponding callback event. The code sample is as follows:
    1. my.offSocketError(this.callback);

my.sendSocketMessage

This API is supported in mPaaS 10.1.60 and later versions.

To send data over a WebSocket connection, you need to first use my.connectSocket to initiate the connection and send the data after the my.onSocketOpen callback.

Input parameter

Name Type Required Description
data String Yes Content that need to be sent: String type plain text content or string type base64 encoded content.
isBuffer Boolean No If you need to send binary data, the data of input parameter should be base64 encoded to string and then assigned to data, meanwhile this field should be set to true. If the data is normal text String, you do not need to set this field.
success Function No Callback function
fail Function No Callback function for failed call
complete Function No Callback function for ended call (executed regardless of whether the call is successful or failed)

Code sample

The code is for reference only, it is recommended to use your own address for testing.

  1. my.sendSocketMessage({
  2. data: this.data.toSendMessage, // Content to be sent
  3. success: (res) => {
  4. my.alert({content: 'Data sent!' + this.data.toSendMessage});
  5. },
  6. });

my.onSocketMessage

This API is supported in mPaaS 10.1.60 and later versions.

Listen to the event that WebSocket receives messages from the server.

Callback return value

Name Type Description
data String/ArrayBuffer Message returned by the server: String type plain text content or string type base64 encoded content
isBuffer Boolean If this field is true, the data field indicates that the base64-encoded string was received, otherwise the data field indicates that the normal text string was received.

Code sample

The code is for reference only, it is recommended to use your own address for testing.

  1. my.connectSocket({
  2. url: 'Server address'
  3. })
  4. my.onSocketMessage(function(res) {
  5. console.log('Content received from the server:' + res.data)
  6. })

my.offSocketMessage

This API is supported in mPaaS 10.1.60 and later versions.

Cancel the listening of event that WebSocket receives messages from the server.

Code sample

The code is for reference only, it is recommended to use your own address for testing.

  1. my.connectSocket({
  2. url: 'Server address'
  3. })
  4. my.onSocketMessage(function(res) {
  5. console.log('Received server content:' + res.data)
  6. })
  7. my.offSocketMessage();

Whether to pass the callback value

  • If the callback value is not passed, all event callbacks will be removed. The code sample is as follows:
    1. my.offSocketMessage();
  • If the callback value is passed, only remove the corresponding callback event. The code sample is as follows:
    1. my.offSocketMessage(this.callback);

my.closeSocket

This API is supported in mPaaS 10.1.60 and later versions.

Close the WebSocket connection.

Input parameter

Name Type Required Description
success Function No Callback function
fail Function No Callback function for failed call
complete Function No Callback function for ended call (executed regardless of whether the call is successful or failed)

Code sample

The code is for reference only, it is recommended to use your own address for testing.

  1. my.onSocketOpen(function() {
  2. my.closeSocket()
  3. })
  4. my.onSocketClose(function(res) {
  5. console.log('WebSocket is closed! ')
  6. })

my.onSocketClose

This API is supported in mPaaS 10.1.60 and later versions.

Listen to WebSocket close.

Input parameter

Name Type Required Description
callback Function Yes The callback function of WebSocket connection closed event.

Code sample

The code is for reference only, it is recommended to use your own address for testing.

  1. onLoad() {
  2. // Note: The registration of callback method only needs to be done once during the startup phase of the mini program, and there will be several callbacks when the callback method is invoked several times.
  3. my.onSocketClose((res) => {
  4. my.alert({content: 'Connection is closed! '});
  5. this.setData({
  6. sendMessageAbility: false,
  7. closeLinkAbility: false,
  8. });
  9. });
  10. // Note: The registration of callback method only needs to be done once during the startup phase of the mini program, and there will be several callbacks when the callback method is invoked several times.
  11. my.onSocketOpen((res) => {
  12. my.alert({content: 'Connection is established! '});
  13. this.setData({
  14. sendMessageAbility: true,
  15. closeLinkAbility: true,
  16. });
  17. });
  18. my.onSocketError(function(res){
  19. my.alert('WebSocket connection failed to establish, please check!' + res);
  20. });
  21. // Note: The registration of callback method only needs to be done once during the startup phase of the mini program, and there will be several callbacks when the callback method is invoked several times.
  22. my.onSocketMessage((res) => {
  23. my.alert({content: 'Received data!' + JSON.stringify(res)});
  24. });
  25. }
  26. connect_start() {
  27. my.connectSocket({
  28. url: 'Server address', // The developer's server address must use wss protocol, and the domain name must be a legal domain name configured in the background
  29. success: (res) => {
  30. my.showToast({
  31. content: 'success', // Text content
  32. });
  33. },
  34. fail:()=>{
  35. my.showToast({
  36. content: 'fail', // Text content
  37. });
  38. }
  39. });
  40. },

my.offSocketClose

This API is supported in mPaaS 10.1.60 and later versions.

Cancel listening of WebSocket shutdown.

Code sample

The code is for reference only, it is recommended to use your own address for testing.

  1. Page({
  2. onLoad() {
  3. my.onSocketClose(this.callback);
  4. },
  5. onUnload() {
  6. my.offSocketClose(this.callback);
  7. // my.offSocketClose();
  8. },
  9. callback(res) {
  10. my.alert({content: 'Connection closed!'});
  11. this.setData({
  12. sendMessageAbility: false,
  13. closeLinkAbility: false,
  14. });
  15. },
  16. })

Whether to pass the callback value

  • If the callback value is not passed, all event callbacks will be removed. The code sample is as follows:
    1. my.offSocketClose();
  • If the callback value is passed, only remove the corresponding callback event. The code sample is as follows:
    1. my.offSocketClose(this.callback);