Table of Contents
How to Use uni.request API for Making HTTP Requests
What are the Common Error Handling Techniques When Using uni.request in uni-app?
How Can I Integrate uni.request with My uni-app Project's Authentication System?
Can I Use uni.request to Upload Files in My uni-app Project?
Home Web Front-end uni-app How do I use uni-app's uni.request API for making HTTP requests?

How do I use uni-app's uni.request API for making HTTP requests?

Mar 11, 2025 pm 07:13 PM

How to Use uni.request API for Making HTTP Requests

The uni.request API in uni-app is a versatile tool for making HTTP requests to various servers. It's a wrapper around the native XMLHttpRequest object, providing a more convenient and cross-platform approach. Here's a detailed breakdown of how to use it:

Basic Usage:

The core function is uni.request(), which takes an options object as its argument. This object specifies the request details. A simple GET request might look like this:

uni.request({
  url: 'https://api.example.com/data',
  method: 'GET',
  success: (res) => {
    console.log('Request successful:', res.data);
  },
  fail: (err) => {
    console.error('Request failed:', err);
  },
  complete: (res) => {
    console.log('Request completed:', res);
  }
});
Copy after login

This code sends a GET request to https://api.example.com/data. The success callback handles successful responses, fail handles errors, and complete executes regardless of success or failure. res.data contains the response data.

Advanced Options:

uni.request supports various options for customizing your requests:

  • method: Specifies the HTTP method (GET, POST, PUT, DELETE, etc.). Defaults to GET.
  • data: The data to send with the request (usually for POST, PUT, etc.). This can be an object or a string.
  • header: An object containing HTTP headers (e.g., Content-Type, Authorization).
  • dataType: Specifies the expected data type of the response ('json' is common).
  • responseType: Specifies the expected response type ('text', 'arraybuffer', etc.).
  • timeout: Sets a timeout for the request in milliseconds.

Example POST request:

uni.request({
  url: 'https://api.example.com/submit',
  method: 'POST',
  header: {
    'Content-Type': 'application/json'
  },
  data: {
    name: 'John Doe',
    email: 'john.doe@example.com'
  },
  success: (res) => {
    // ...
  },
  fail: (err) => {
    // ...
  }
});
Copy after login

What are the Common Error Handling Techniques When Using uni.request in uni-app?

Robust error handling is crucial for a smooth user experience. Here are common techniques for handling errors with uni.request:

  • fail Callback: The fail callback is the primary mechanism. It receives an error object containing information about the failure (e.g., status code, error message). Use this to provide informative error messages to the user or log the error for debugging.
  • Status Code Checking: Check the HTTP status code in the fail callback (or even in complete for more comprehensive handling). Different status codes indicate different issues (404 Not Found, 500 Internal Server Error, etc.). Handle these cases differently, providing tailored user feedback.
  • Network Error Handling: Detect network connectivity issues. uni.request might fail due to a lack of internet connection. You can use uni.getSystemInfoSync().networkType to check the network status before making the request or handle network errors specifically within the fail callback.
  • Try...Catch Blocks: While less common with uni.request which already provides callbacks, you could wrap the uni.request call in a try...catch block to catch unexpected errors that might occur outside the request itself (e.g., JSON parsing errors).
  • Generic Error Handling: Provide a generic error message to the user if the specific error is unclear or too technical. Log the full error details for debugging purposes.

Example with status code checking:

uni.request({
  // ... request options ...
  fail: (err) => {
    if (err.statusCode === 404) {
      uni.showToast({ title: 'Resource not found', icon: 'error' });
    } else if (err.statusCode === 500) {
      uni.showToast({ title: 'Server error', icon: 'error' });
    } else {
      uni.showToast({ title: 'An error occurred', icon: 'error' });
      console.error('Request failed:', err);
    }
  }
});
Copy after login

How Can I Integrate uni.request with My uni-app Project's Authentication System?

Integrating uni.request with an authentication system typically involves adding an Authorization header to each request. This header usually contains a token (JWT, session ID, etc.) that identifies the authenticated user.

Implementation:

  1. Token Storage: Store the authentication token securely (e.g., in uni-app's storage using uni.setStorageSync and uni.getStorageSync).
  2. Header Injection: Before making each request, retrieve the token and add it to the header object:
const token = uni.getStorageSync('token');

uni.request({
  url: 'https://api.example.com/protected-data',
  header: {
    'Authorization': `Bearer ${token}` // Adjust as needed for your auth scheme
  },
  success: (res) => {
    // ...
  },
  fail: (err) => {
    // Handle authentication errors (e.g., 401 Unauthorized)
    if (err.statusCode === 401) {
      // Redirect to login or refresh token
    }
  }
});
Copy after login
  1. Token Refreshing: Implement token refreshing if your authentication system uses short-lived tokens. Check the token's expiration and automatically refresh it before it expires. This usually involves making a separate request to a token refresh endpoint.
  2. Error Handling: Handle authentication errors (like 401 Unauthorized) appropriately. This might involve redirecting the user to the login page or prompting them to re-authenticate.

Can I Use uni.request to Upload Files in My uni-app Project?

Yes, uni.request can upload files, but it requires using the formData API. Here's how:

Implementation:

  1. Create FormData: Create a FormData object and append the file to it. You'll need to access the file using the appropriate uni-app file selection API (e.g., uni.chooseImage or uni.chooseVideo).
  2. Set Content-Type: Set the Content-Type header to multipart/form-data.
  3. Send the Request: Send a POST request with the FormData object as the data.

Example:

uni.chooseImage({
  count: 1,
  success: (res) => {
    const filePath = res.tempFiles[0].path;
    const formData = new FormData();
    formData.append('file', {
      uri: filePath,
      name: 'file.jpg', // Adjust filename as needed
      type: 'image/jpeg' // Adjust file type as needed
    });

    uni.request({
      url: 'https://api.example.com/upload',
      method: 'POST',
      header: {
        'Content-Type': 'multipart/form-data'
      },
      data: formData,
      success: (res) => {
        // ...
      },
      fail: (err) => {
        // ...
      }
    });
  }
});
Copy after login

Remember to adjust the name and type properties according to your uploaded file. The server-side needs to be configured to handle multipart/form-data uploads. Also, consider using a progress indicator to show upload progress to the user for a better user experience, which usually requires a different approach beyond the basic uni.request.

The above is the detailed content of How do I use uni-app's uni.request API for making HTTP requests?. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I use uni-app's social sharing APIs? How do I use uni-app's social sharing APIs? Mar 13, 2025 pm 06:30 PM

The article details how to integrate social sharing into uni-app projects using uni.share API, covering setup, configuration, and testing across platforms like WeChat and Weibo.

How do I use preprocessors (Sass, Less) with uni-app? How do I use preprocessors (Sass, Less) with uni-app? Mar 18, 2025 pm 12:20 PM

Article discusses using Sass and Less preprocessors in uni-app, detailing setup, benefits, and dual usage. Main focus is on configuration and advantages.[159 characters]

How do I use uni-app's animation API? How do I use uni-app's animation API? Mar 18, 2025 pm 12:21 PM

The article explains how to use uni-app's animation API, detailing steps to create and apply animations, key functions, and methods to combine and control animation timing.Character count: 159

What are the different types of testing that you can perform in a UniApp application? What are the different types of testing that you can perform in a UniApp application? Mar 27, 2025 pm 04:59 PM

The article discusses various testing types for UniApp applications, including unit, integration, functional, UI/UX, performance, cross-platform, and security testing. It also covers ensuring cross-platform compatibility and recommends tools like Jes

How can you reduce the size of your UniApp application package? How can you reduce the size of your UniApp application package? Mar 27, 2025 pm 04:45 PM

The article discusses strategies to reduce UniApp package size, focusing on code optimization, resource management, and techniques like code splitting and lazy loading.

How do I use uni-app's storage API (uni.setStorage, uni.getStorage)? How do I use uni-app's storage API (uni.setStorage, uni.getStorage)? Mar 18, 2025 pm 12:22 PM

The article explains how to use uni-app's storage APIs (uni.setStorage, uni.getStorage) for local data management, discusses best practices, troubleshooting, and highlights limitations and considerations for effective use.

What is the file structure of a uni-app project? What is the file structure of a uni-app project? Mar 14, 2025 pm 06:55 PM

The article details the file structure of a uni-app project, explaining key directories like common, components, pages, static, and uniCloud, and crucial files such as App.vue, main.js, manifest.json, pages.json, and uni.scss. It discusses how this o

How can you optimize images for web performance in UniApp? How can you optimize images for web performance in UniApp? Mar 27, 2025 pm 04:50 PM

The article discusses optimizing images in UniApp for better web performance through compression, responsive design, lazy loading, caching, and using WebP format.

See all articles