All Products
Search
Document Center

Mobile Platform as a Service:Network

Last Updated:Sep 11, 2023

my.request

Network request of a Mini Program.

  • my.request currently supports GET/POST/DELETE.

  • my.request currently only supports HTTPS protocol requests.

  • Note

    Basic library 1.11.0 and above support this interface and can usemy.canIUse('request')for compatibility processing. For more details, please refer to Mini program base library.

    This interface is supported by mPaaS 10.1.60 and above.

    Interfacemy.httpRequest will be deprecated, please use interface my.request instead.

    The default value ofmy.request's request header 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 type String.

For more information, see my.request FAQ.

Instructions for use:

  • You need to turn on the Permission control switch of the mini program 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).

  • 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/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.

Code sample

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

my.request({
  url: 'https://example.org/post',
  method: 'POST',
  data: {
    from: 'Alipay',
    production: 'AlipayJSAPI',
  },
  dataType: 'json',
  success: function(res) {
    my.alert({content: 'success'});
  },
  fail: function(res) {
    my.alert({content: 'fail'});
  },
  complete: function(res) {
    my.hideLoading();
    my.alert({content: 'complete'});
  }
});

// Return RequestTask, you can call abort method to cancel the request
const task = my.request({url: 'https://example.org/post'})
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).

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

my.uploadFile({
  url: 'Please use your own server address',
  fileType: 'image',
  fileName: 'file',
  filePath: '...',
  success: (res) => {
    my.alert({
      content: 'Upload successful'
    });
  },
});

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

const task = my.uploadFile({
  url: 'Please use your own server address',
  fileType: 'image',
  fileName: 'file',
  filePath: '...',
});
task.onProgressUpdate(({progress, totalBytesWritten, totalBytesExpectedToWrite}) => {
})
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.

// API-DEMO page/API/download-file/download-file.json
{
    "defaultTitle": "Download file"
}
<!-- API-DEMO page/API/download-file/download-file.axml-->
<view class="container">
  <button onTap="download">Download image and display</button>
</view>
// API-DEMO page/API/download-file/download-file.js
Page({
  download() {
    my.downloadFile({
      url: 'https://img.alicdn.com/tfs/TB1x669SXXXXXbdaFXXXXXXXXXX-520-280.jpg',
      success({ apFilePath }) {
        my.previewImage({
          urls: [apFilePath],
        });
      },
      fail(res) {
        my.alert({
          content: res.errorMessage || res.error,
        });
      },
    });
  },
})

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.

my.connectSocket({
  url: 'test.php',
  data: {},
  header:{
    'content-type': 'application/json'
  },
});

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.

my.connectSocket({
  url: 'test.php',
});

my.onSocketOpen(function(res) {
  console.log('WebSocket connection is established! ');
});

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.

Page({
  onLoad() {
    this.callback = this.callback.bind(this);
    my.onSocketOpen(this.callback);
  },
  onUnload() {
    my.offSocketOpen(this.callback);
  },
  callback(res) {
  },
})

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:

    my.offSocketOpen();
  • If the callback value is passed, only remove the corresponding callback event. The code sample is as follows:

    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.

my.connectSocket({
  url: 'Developer server address'
});

my.onSocketOpen(function(res){
  console.log('WebSocket connection is established! ');
});

my.onSocketError(function(res){
  console.log('WebSocket connection failed to establish, please check! ');
});

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.

Page({
  onLoad() {
    this.callback = this.callback.bind(this);
    my.onSocketError(this.callback);
  },
  onUnload() {
    my.offSocketError(this.callback);
  },
  callback(res) {
  },
})

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:

    my.offSocketError();
  • If the callback value is passed, only remove the corresponding callback event. The code sample is as follows:

    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.

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

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.

my.connectSocket({
  url: 'Server address'
})

my.onSocketMessage(function(res) {
  console.log('Content received from the server:' + res.data)
})

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.

my.connectSocket({
  url: 'Server address'
})
my.onSocketMessage(function(res) {
  console.log('Received server content:' + res.data)
})
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:

    my.offSocketMessage();
  • If the callback value is passed, only remove the corresponding callback event. The code sample is as follows:

    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.

my.onSocketOpen(function() {
  my.closeSocket()
})

my.onSocketClose(function(res) {
  console.log('WebSocket is closed! ')
})

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.

onLoad() {
    // 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.
    my.onSocketClose((res) => {
      my.alert({content: 'Connection is closed! '});
      this.setData({
        sendMessageAbility: false,
        closeLinkAbility: false,
      });
    });
    // 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.
    my.onSocketOpen((res) => {
      my.alert({content: 'Connection is established! '});
      this.setData({
        sendMessageAbility: true,
        closeLinkAbility: true,
      });
    });

    my.onSocketError(function(res){
      my.alert('WebSocket connection failed to establish, please check!' + res);
    });

    // 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.
    my.onSocketMessage((res) => {
      my.alert({content: 'Received data!' + JSON.stringify(res)});
    });
  }

connect_start() {
    my.connectSocket({
      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
      success: (res) => {
        my.showToast({
          content: 'success', // Text content
        });
      },
      fail:()=>{
        my.showToast({
          content: 'fail', // Text content
        });
      }
    });
  },

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.

Page({
  onLoad() {
  my.onSocketClose(this.callback);
  },
  onUnload() {
    my.offSocketClose(this.callback);
    //    my.offSocketClose();
  },
  callback(res) {
  my.alert({content: 'Connection closed!'});
      this.setData({
        sendMessageAbility: false,
        closeLinkAbility: false,
      });
  },
})

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:

    my.offSocketClose();
  • If the callback value is passed, only remove the corresponding callback event. The code sample is as follows:

    my.offSocketClose(this.callback);

my.rpc(Object)

Mini program framework dedicated rpc interface, and mini program gateway interface.

Parameter description

Name

Type

Required

Description

operationType

String

Yes

Gateway operationtype.

requestData

Array

No

Gateway requests data.

success

Function

No

Invoke the successful callback function.

fail

Function

No

Callback function that failed to be called.

complete

Function

No

The callback function for the end of the call (both the call succeeds and fails).

Code sample

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

my.rpc({
      operationType: 'com.xx.xx',
      requestData: [{
        "param1":"",
        "param2":0
      }],
      success: res => {
      },
      fail: res => {
      }
});