All Products
Search
Document Center

Mobile Platform as a Service:Network

Last Updated:Feb 02, 2026

my.request

Makes a network request from a miniapp.

  • The my.request API currently supports the GET, POST, and DELETE methods.

  • The my.request API currently supports only HTTPS requests.

Note
  • This API is supported in base library versions 1.11.0 and later. You can use my.canIUse('request') to handle compatibility. For more information, see Mini Program Base Library Description.

  • This API is supported in mPaaS 10.1.60 and later.

  • The my.httpRequest API is deprecated. Use my.request instead.

  • The default request header for my.request is {'content-type': 'application/json'}, not {'content-type': 'application/x-www-form-urlencoded'}. The keys and values in the request header object must be strings.

For more information, see my.request FAQ.

Usage notes:

  • Enable the Permission control switch in Release Mini Program > Open Platform Mini Program Management. Then, configure the domain name whitelist in Server domain name whitelist. The miniapp can communicate only with domain names in the whitelist when calling APIs such as HTTP requests (my.request) and file uploads (my.uploadFile).

  • After you add a domain name to the server domain name whitelist, you must repackage, upload, and generate a trial version for the change to take effect.

  • When you debug in the IDE, use a real device for the preview.

Input parameters

Name

Type

Required

Description

url

String

Yes

The URL of the target server.

headers

Object

No

Sets the HTTP request header. The default value is {'content-type': 'application/json'}. The keys and values in this object must be strings.

method

String

No

The default value is GET. GET, POST, and DELETE are supported.

data

Object / ArrayBuffer

No

For more information, see the data parameter description below.

timeout

Number

No

The timeout period in milliseconds (ms). The default value is 30000.

dataType

String

No

The expected data format of the response. The default value is json. Supported formats include json, text, base64, and arraybuffer.

success

Function

No

The callback function for a successful call.

fail

Function

No

The callback function for a failed call.

complete

Function

No

The callback function that is executed at the end of a call, regardless of whether the call is successful or fails.

data parameter description

Data sent to the server is ultimately converted to a string. If the data is not a string, it is converted based on the following rules:

  • If the method is GET, the data is converted to a query string: encodeURIComponent(k)=encodeURIComponent(v)&encodeURIComponent(k)=encodeURIComponent(v)....

  • If the method is POST and headers['content-type'] is application/json, the data is serialized to JSON.

  • If the method is POST and headers['content-type'] is application/x-www-form-urlencoded, the data is converted to a query string: encodeURIComponent(k)=encodeURIComponent(v)&encodeURIComponent(k)=encodeURIComponent(v)....

referer description

  • You cannot set the referer header of a network request.

  • Its format is fixed as https://urlhost/{appid}/{version}/page-frame.html, where {appid} is the APPID of the miniapp and {version} is the version number of the miniapp.

success return value

Name

Type

Description

data

String

The response data. The format depends on the dataType parameter of the request.

status

Number

The response code.

headers

Object

The response header.

Error codes

Error code

Description

Solutions

1

Navigation to another page occurred before the request was complete.

Wait for the request to complete before you navigate to another page.

2

Parameter error.

  • The URL may be too long. Place the parameters in the `data` field.

  • Check whether the request data is valid and correctly formatted. Before you send the request, print the input parameters to a log.

11

No permission for cross-domain request.

Check whether the request domain name is in the domain name whitelist. To test the development version, click Details in the upper-right corner of the IDE and select Ignore httpRequest domain name validity check. Note: When you release a new version, you must add the domain name to the Server Domain Name Whitelist. Otherwise, errors will occur.

12

Network error.

Check whether the network environment is stable and the server is running correctly.

13

Timeout.

Check whether the network environment is stable and the server is responding correctly. If the request takes a long time, set a longer timeout period for the `timeout` parameter.

14

Decoding failed.

Check whether the data formats of the request and response are consistent between the frontend and backend. For example, if the response data format is `text` but the input parameter `dataType` is `JSON`, the API reports an error. In this case, change the backend response data format to JSON.

15

Failed to pass parameters.

If you use `urlencode` to pass parameters from a miniapp page, encode the entire set of parameters.

19

HTTP error.

  • Confirm that the request URL can be accessed over the HTTPS protocol from the public internet. On a real device, miniapp requests are production requests and cannot be sent to a local area network (LAN).

  • If you encounter HTTP errors such as 404, 500, or 504, open the IDE debugger and go to the Network tab to view detailed error information. Then, handle the error based on the HTTP error code.

  • The SSL certificate is incorrect. Replace the website's SSL certificate.

20

Request stopped or throttled by the server.

Confirm that the request server can be accessed and can respond correctly.

23

Agent request failed.

Check whether the agent configuration is correct.

Note

When the input parameter dataType is set to json, the miniapp framework first performs a JSON.parse operation on the result. If parsing fails, the framework returns an error with code 14. When the input parameter dataType is set to text, if the format of the returned content does not match, the framework also returns an error with code 14. If you encounter this error, first check whether the dataType is set correctly.

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

Code example

This example is for reference only. You must 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'});
  }
});

// Returns a RequestTask, which lets you call the abort method to cancel the request.
const task = my.request({url: 'https://example.org/post'})
task.abort()

Return value

RequestTask

A network request task object.

Method

RequestTask.abort()

my.uploadFile

Note

This API is supported in mPaaS 10.1.32 and later.

Uploads a local resource to the developer's server.

Usage notes:

  • Configure the domain name whitelist in Open Platform Mini Program Management > Server Domain Name Whitelist. The miniapp can communicate only with domain names in the whitelist when calling APIs such as HTTP requests (my.request) and file uploads (my.uploadFile).

Input parameters

Name

Type

Required

Description

url

String

Yes

The developer's server address.

filePath

String

Yes

The local identifier of the file resource to upload.

fileName

String

Yes

The file name, which is the corresponding key. The developer can get the binary content of the file on the server side through this key.

fileType

String

Yes

The file type: image, video, or audio.

hideLoading

Bool

No

Specifies whether to hide the loading icon. The default value is false.

header

Object

No

The HTTP request header.

formData

Object

No

Other extra form data in the HTTP request.

success

Function

No

The callback function for a successful call.

fail

Function

No

The callback function for a failed call.

complete

Function

No

The callback function that is executed at the end of a call, regardless of whether the call is successful or fails.

success return value

Name

Type

Description

data

String

The data returned by the server.

statusCode

String

The HTTP status code.

header

Object

The header returned by the server.

Error codes

error

Description

Solutions

11

File does not exist.

Check if the local file exists.

12

File upload failed.

Check the network and the server.

13

No permission.

Check the permission settings.

Code example

This example is for reference only. You must use your own address for testing.

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

UploadTask

An object that listens for upload progress changes and cancels upload tasks.

Methods

Method

Description

UploadTask.abort()

Breaks the upload task.

UploadTask.onProgressUpdate(function callback)

Listens for upload progress change events.

Code example

const task = my.uploadFile({
  url: 'Use your own server address',
  fileType: 'image',
  fileName: 'file',
  filePath: '...',
});
task.onProgressUpdate(({progress, totalBytesWritten, totalBytesExpectedToWrite}) => {
})
task.abort()

FAQ

  • Q: Can a miniapp automatically convert an uploaded image to Base64, which is a method of representing binary data with printable characters?

    A: No, miniapps do not support converting images to Base64.

  • Q: How can I use my.uploadFile to retrieve error messages returned from the server?

    A:

    • Retrieve it from the `data` parameter in the `success` callback.

    • Add a log retrieval API on the server side. If an upload fails, call the log retrieval API to obtain detailed failure logs.

  • Q: What is the default timeout for my.uploadFile? Can the default timeout be extended?

    A: The default timeout for my.uploadFile is 30 s. No, you cannot extend the default timeout.

  • Q: Why does my.uploadFile report error: 12 when uploading a file?

    A: The error code 12 indicates an upload failure. Possible reasons for the failure include the following:

    • The file is too large.

    • The upload took longer than 30 s.

    • No permission.

  • Q: The backend receives a binary image when my.uploadFile is used. If the backend sends this binary image back to the miniapp, how does the miniapp parse it?

    A: The backend receives the image as a binary stream. The backend only needs to provide the URL of the image's location on the server.

  • Q: Why does calling my.uploadFile report error: 4, no permission to call this API?

    A: The requested URL is not in the whitelist. Add the URL's domain name to the whitelist.

  • Q: Do miniapps support uploading Excel files?

    A: No. Currently, my.uploadFile supports uploading files of the type image, video, or audio. Other file types are not supported.

  • Q: Does my.uploadFile support uploading multiple images at the same time?

    A: No, my.uploadFile does not support uploading multiple images at the same time. You can upload only one image at a time.

my.downloadFile

Note

This API is supported in mPaaS 10.1.32 and later.

Downloads a file resource to the local device.

Input parameters

Name

Type

Required

Description

url

String

Yes

The address of the file to download.

header

Object

No

The HTTP request header.

success

Function

No

The callback function for a successful call.

fail

Function

No

The callback function for a failed call.

complete

Function

No

The callback function that is executed at the end of a call, regardless of whether the call is successful or fails.

success return value

Name

Type

Description

apFilePath

String

The temporary location where the file is stored.

Error codes

error

Description

Solutions

12

Download failed.

Check the network and the server.

13

No permission.

Check the permissions.

20

The requested URL does not support HTTP.

Change the requested URL to use HTTPS.

Code example

This example is for reference only. You must 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 and display image</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

Note

This API is supported in mPaaS 10.1.60 and later.

Creates a WebSocket connection.

A miniapp can have only one WebSocket connection at a time. If a WebSocket connection already exists, it is automatically closed, and a new one is created.

Input parameters

Name

Type

Required

Description

url

String

Yes

The URL of the target server. Note: Some newly released miniapps support only the wss protocol.

data

Object

No

The request parameters.

header

Object

No

Sets the request header.

success

Function

No

The callback function for a successful call.

fail

Function

No

The callback function for a failed call.

complete

Function

No

The callback function that is executed at the end of a call, regardless of whether the call is successful or fails.

Error codes

error

Description

Solutions

1

Unknown error.

-

2

The network connection already exists.

A miniapp can have only one WebSocket connection at a time. If a WebSocket connection already exists, it is automatically closed, and a new one is created.

3

The URL parameter is empty.

Replace the URL.

4

Unrecognized URL format.

Provide a URL with a valid format.

5

The URL must start with ws or wss.

Replace the URL.

6

Connection to the server timed out.

Try again later.

7

The HTTPS certificate returned by the server is invalid.

Miniapps must use HTTPS or WSS to initiate network requests. When a request is made, the system verifies the HTTPS certificate that is used by the server domain name. If the verification fails, the request cannot be initiated. Due to system limitations, different platforms have different levels of strictness for certificate requirements. To ensure compatibility, configure certificates according to the highest standards and use relevant tools to check that your existing certificates meet the requirements.

8

The protocol header returned by the server is invalid.

Starting from May 2019, newly created miniapps must use the HTTPS and WSS protocols. The HTTP and WS protocols are no longer supported.

9

The WebSocket request did not specify the Sec-WebSocket-Protocol request header.

Specify the Sec-WebSocket-Protocol request header.

10

The network connection is not open, so a message cannot be sent.

Connect to the server before you call my.sendSocketMessage to send a data message. You can use my.onSocketOpen to listen for the event to determine whether a correct connection has been established with the server. Note: To send data over a WebSocket connection, first use my.connectSocket to initiate the connection. Then, call my.sendSocketMessage to send data after the my.onSocketOpen callback.

11

Message sending failed.

Try again later.

12

Cannot request more memory to read network data.

Check the memory.

Code example

This example is for reference only. You must use your own address for testing.

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

my.onSocketOpen

Note

This API is supported in mPaaS 10.1.60 and later.

Listens for the WebSocket connection open event.

Input parameters

Object type with the following properties:

Property

Type

Required

Description

callback

Function

Yes

The callback function for the WebSocket connection open event.

Code example

This example is for reference only. You must use your own address for testing.

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

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

my.offSocketOpen

Note

This API is supported in mPaaS 10.1.60 and later.

Stops listening for the WebSocket connection open event.

Code example

This example is for reference only. You must 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 a callback value

  • If you do not pass a callback value, all event callbacks for this listener are removed. The following code provides an example:

    my.offSocketOpen();
  • If you pass a callback value, only the corresponding callback event is removed. The following code provides an example:

    my.offSocketOpen(this.callback);

my.onSocketError

Note

This API is supported in mPaaS 10.1.60 and later.

Listens for WebSocket errors.

Input parameters

Object type with the following properties:

Parameter

Type

Required

Description

callback

Function

Yes

The callback function for the WebSocket error event.

Code example

This example is for reference only. You must use your own address for testing.

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

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

my.onSocketError(function(res){
  console.log('WebSocket connection failed. Please check!');
});

my.offSocketError

Note

This API is supported in mPaaS 10.1.60 and later.

Stops listening for WebSocket errors.

Code example

This example is for reference only. You must 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 a callback value

  • If you do not pass a callback value, all event callbacks for this listener are removed. The following code provides an example:

    my.offSocketError();
  • If you pass a callback value, only the corresponding callback event is removed. The following code provides an example:

    my.offSocketError(this.callback);

my.sendSocketMessage

Note

This API is supported in mPaaS 10.1.60 and later.

Sends data over a WebSocket connection. You must first use my.connectSocket to initiate a connection and then send data after the my.onSocketOpen callback.

Input parameters

Name

Type

Required

Description

data

String

Yes

The content to send: a plain text string or a Base64-encoded string.

isBuffer

Boolean

No

To send binary data, Base64-encode the input data into a string, assign it to data, and set this field to true. If the data is a plain text string, you do not need to set this field.

success

Function

No

The callback function.

fail

Function

No

The callback function for a failed call.

complete

Function

No

The callback function that is executed at the end of a call, regardless of whether the call is successful or fails.

Code example

This example is for reference only. You must use your own address for testing.

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

my.onSocketMessage

Note

This API is supported in mPaaS 10.1.60 and later.

Listens for messages received from the server over a WebSocket connection.

Callback return value

Name

Type

Description

data

String/ArrayBuffer

The message returned by the server: a plain text string or a Base64-encoded string.

isBuffer

Boolean

If this field is true, the data field represents a received Base64-encoded string. Otherwise, the data field represents a received plain text string.

Code example

This example is for reference only. You must use your own address for testing.

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

my.onSocketMessage(function(res) {
  console.log('Received server content: ' + res.data)
})

my.offSocketMessage

Note

This API is supported in mPaaS 10.1.60 and later.

Stops listening for messages received from the server over a WebSocket connection.

Code example

This example is for reference only. You must 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 a callback value

  • If you do not pass a callback value, all event callbacks for this listener are removed. The following code provides an example:

    my.offSocketMessage();
  • If you pass a callback value, only the corresponding callback event is removed. The following code provides an example:

    my.offSocketMessage(this.callback);

my.closeSocket

Note

This API is supported in mPaaS 10.1.60 and later.

Closes a WebSocket connection.

Input parameters

Name

Type

Required

Description

success

Function

No

The callback function.

fail

Function

No

The callback function for a failed call.

complete

Function

No

The callback function that is executed at the end of a call, regardless of whether the call is successful or fails.

Code example

This example is for reference only. You must use your own address for testing.

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

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

my.onSocketClose

Note

This API is supported in mPaaS 10.1.60 and later.

Listens for the WebSocket close event.

Input parameters

Object type with the following properties:

Parameter

Type

Required

Description

callback

Function

Yes

The callback function for the WebSocket connection close event.

Code example

This example is for reference only. You must use your own address for testing.

onLoad() {
    // Note: Register the callback method only once during the miniapp startup phase.
    // If you call it multiple times, the callback will be triggered multiple times.
    my.onSocketClose((res) => {
      my.alert({content: 'Connection closed!'});
      this.setData({
        sendMessageAbility: false,
        closeLinkAbility: false,
      });
    });
    // Note: Register the callback method only once during the miniapp startup phase.
    // If you call it multiple times, the callback will be triggered multiple times.
    my.onSocketOpen((res) => {
      my.alert({content: 'Connection opened!'});
      this.setData({
        sendMessageAbility: true,
        closeLinkAbility: true,
      });
    });

    my.onSocketError(function(res){
      my.alert('WebSocket connection failed. Please check! ' + res);
    });

    // Note: Register the callback method only once during the miniapp startup phase.
    // If you call it multiple times, the callback will be triggered multiple times.
    my.onSocketMessage((res) => {
      my.alert({content: 'Data received! ' + JSON.stringify(res)});
    });
  }

connect_start() {
    my.connectSocket({
      url: 'Server address', // The developer's server API address. It must use the wss protocol, and the domain name must be a legitimate domain name configured in the backend.
      success: (res) => {
        my.showToast({
          content: 'success', // Text content
        });
      },
      fail:()=>{
        my.showToast({
          content: 'fail', // Text content
        });
      }
    });
  },

my.offSocketClose

Note

This API is supported in mPaaS 10.1.60 and later.

Stops listening for the WebSocket close event.

Code example

This example is for reference only. You must 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 a callback value

  • If you do not pass a callback value, all event callbacks for this listener are removed. The following code provides an example:

    my.offSocketClose();
  • If you pass a callback value, only the corresponding callback event is removed. The following code provides an example:

    my.offSocketClose(this.callback);

my.rpc(Object)

A dedicated remote procedure call (RPC) API for the miniapp framework. It is the miniapp gateway API.

Parameter description

Name

Type

Required

Description

operationType

String

Yes

The gateway operationType.

requestData

Array

No

The gateway request data.

success

Function

No

The callback function for a successful call.

fail

Function

No

The callback function for a failed call.

complete

Function

No

The callback function that is executed at the end of a call, regardless of whether the call is successful or fails.

Code example

This example is for reference only. You must use your own address for testing.

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