or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

app-component-creation.mdautomation.mdbuild-configuration.mdindex.mdnavigation-apis.mdnetwork-apis.mdruntime-api.mdsystem-apis.mdvue-integration.md
tile.json

network-apis.mddocs/

Network APIs

Network communication APIs for HTTP requests and WebSocket connections with Baidu-specific protocol adaptations and parameter transformations.

Capabilities

HTTP Request

Make HTTP requests with cross-platform compatibility and Baidu Smart Program specific enhancements.

/**
 * Make an HTTP request
 * @param options - Request configuration options
 * @returns Promise that resolves with the response
 */
function request(options: RequestOptions): Promise<RequestResult>;

interface RequestOptions {
  url: string; // Request URL
  data?: any; // Request data (object or string)
  header?: any; // Request headers
  method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'CONNECT' | 'HEAD' | 'OPTIONS' | 'TRACE'; // HTTP method
  timeout?: number; // Request timeout in milliseconds
  dataType?: 'json' | 'text' | 'base64'; // Expected response data type
  responseType?: 'text' | 'arraybuffer'; // Response type
  success?(result: RequestResult): void;
  fail?(error: any): void;
  complete?(): void;
}

interface RequestResult {
  data: any; // Response data
  statusCode: number; // HTTP status code
  header: any; // Response headers
  cookies?: string[]; // Response cookies (if available)
}

Usage Examples:

import uni from "@dcloudio/uni-mp-baidu";

// Simple GET request
uni.request({
  url: 'https://api.example.com/users',
  method: 'GET',
  success: (res) => {
    console.log('Response data:', res.data);
    console.log('Status code:', res.statusCode);
  },
  fail: (err) => {
    console.error('Request failed:', err);
  }
});

// POST request with data
uni.request({
  url: 'https://api.example.com/users',
  method: 'POST',
  data: {
    name: 'John Doe',
    email: 'john@example.com'
  },
  header: {
    'Content-Type': 'application/json'
  },
  dataType: 'json'
}).then((res) => {
  console.log('User created:', res.data);
}).catch((err) => {
  console.error('Error:', err);
});

// Request with custom headers and timeout
uni.request({
  url: 'https://api.example.com/data',
  method: 'GET',
  header: {
    'Authorization': 'Bearer token123',
    'X-Custom-Header': 'value'
  },
  timeout: 10000, // 10 seconds
  dataType: 'json',
  success: (res) => {
    if (res.statusCode === 200) {
      console.log('Success:', res.data);
    } else {
      console.log('HTTP error:', res.statusCode);
    }
  }
});

WebSocket Connection

Create and manage WebSocket connections with Baidu Smart Program compatibility.

/**
 * Create a WebSocket connection
 * @param options - WebSocket connection options
 * @returns SocketTask object for managing the connection
 */
function connectSocket(options: ConnectSocketOptions): SocketTask;

interface ConnectSocketOptions {
  url: string; // WebSocket server URL
  header?: any; // Connection headers
  protocols?: string[]; // WebSocket sub-protocols
  success?(result: any): void;
  fail?(error: any): void;
  complete?(): void;
}

interface SocketTask {
  /** Send data through the WebSocket connection */
  send(options: {
    data: string | ArrayBuffer;
    success?(result: any): void;
    fail?(error: any): void;
    complete?(): void;
  }): void;
  
  /** Close the WebSocket connection */
  close(options?: {
    code?: number;
    reason?: string;
    success?(result: any): void;
    fail?(error: any): void;
    complete?(): void;
  }): void;
  
  /** Listen for connection open event */
  onOpen(callback: (result: { header: any }) => void): void;
  
  /** Listen for connection close event */
  onClose(callback: (result: { code: number; reason: string }) => void): void;
  
  /** Listen for connection error event */
  onError(callback: (error: any) => void): void;
  
  /** Listen for incoming messages */
  onMessage(callback: (result: { data: string | ArrayBuffer }) => void): void;
}

Usage Examples:

// Create WebSocket connection
const socketTask = uni.connectSocket({
  url: 'wss://api.example.com/websocket',
  header: {
    'Authorization': 'Bearer token123'
  },
  protocols: ['chat', 'notification']
});

// Handle connection events
socketTask.onOpen((res) => {
  console.log('WebSocket connected', res);
  
  // Send a message
  socketTask.send({
    data: JSON.stringify({
      type: 'greeting',
      message: 'Hello Server!'
    }),
    success: () => {
      console.log('Message sent successfully');
    }
  });
});

socketTask.onMessage((res) => {
  console.log('Received message:', res.data);
  
  // Handle different message types
  try {
    const message = JSON.parse(res.data);
    switch (message.type) {
      case 'notification':
        console.log('Notification:', message.content);
        break;
      case 'data':
        console.log('Data update:', message.payload);
        break;
    }
  } catch (error) {
    console.error('Invalid JSON message:', res.data);
  }
});

socketTask.onError((error) => {
  console.error('WebSocket error:', error);
});

socketTask.onClose((res) => {
  console.log('WebSocket closed', res.code, res.reason);
});

// Close connection when needed
setTimeout(() => {
  socketTask.close({
    code: 1000,
    reason: 'Normal closure'
  });
}, 30000);

Platform-Specific Features

HTTP Request Adaptations

The request API includes several Baidu Smart Program specific adaptations:

Method Parameter Mapping

  • HTTP methods are normalized for Baidu Smart Program compatibility
  • Unsupported methods are mapped to supported alternatives
  • Parameter validation ensures proper method format

Data Type Handling

  • dataType parameter is transformed for Baidu's expected format
  • Response data is automatically parsed based on the specified data type
  • Enhanced error handling for data type mismatches

Header Processing

  • Request headers are normalized to Baidu Smart Program format
  • Automatic content-type detection and setting
  • Header validation and sanitization

WebSocket Adaptations

Protocol Filtering

  • Unsupported WebSocket parameters (like method) are automatically removed
  • Protocol negotiation is handled transparently
  • Connection options are optimized for Baidu Smart Program environment

Event Handling

  • Event callbacks are enhanced with Baidu-specific event data
  • Error handling includes platform-specific error codes
  • Message handling supports both text and binary data

Error Handling and Retry Logic

// Request with error handling
function makeRequestWithRetry(url, maxRetries = 3) {
  let attempts = 0;
  
  const attemptRequest = () => {
    return uni.request({
      url: url,
      timeout: 5000
    }).catch((error) => {
      attempts++;
      if (attempts < maxRetries) {
        console.log(`Retry attempt ${attempts}/${maxRetries}`);
        return attemptRequest();
      } else {
        throw error;
      }
    });
  };
  
  return attemptRequest();
}

// WebSocket with reconnection logic
function createReconnectingSocket(url) {
  let socket = null;
  let reconnectAttempts = 0;
  const maxReconnectAttempts = 5;
  
  function connect() {
    socket = uni.connectSocket({ url });
    
    socket.onOpen(() => {
      console.log('Connected');
      reconnectAttempts = 0;
    });
    
    socket.onClose(() => {
      if (reconnectAttempts < maxReconnectAttempts) {
        reconnectAttempts++;
        console.log(`Reconnecting... (${reconnectAttempts}/${maxReconnectAttempts})`);
        setTimeout(connect, 2000 * reconnectAttempts);
      }
    });
    
    socket.onError((error) => {
      console.error('Socket error:', error);
    });
  }
  
  connect();
  return socket;
}

Security Considerations

  • All requests must use HTTPS in production Baidu Smart Programs
  • WebSocket connections should use WSS (secure WebSocket) protocol
  • Request headers are sanitized to prevent injection attacks
  • CORS policies are enforced by the Baidu Smart Program runtime