search
HomeWeb Front-enduni-appDetailed introduction to the relevant knowledge of requests and processing results in Uniapp

With the development of the mobile Internet, the market demand for mobile applications is increasing. In response to this demand, various cross-platform frameworks such as React Native and Flutter have emerged. Among them, Uniapp is a framework that can be used to develop cross-platform applications. It can quickly build multiple platforms, such as Android, iOS, Web, WeChat applets, and Alipay applets.

In Uniapp, sending requests and processing request results is a core function. This article will introduce the relevant knowledge of requests and processing results in Uniapp in detail.

1. Request sending

There are many ways to send requests in Uniapp, the most common way is to use the uni.request method.

uni.request({
    url: 'http://www.example.com',
    data: {
        name: 'example'
    },
    header: {
        'content-type': 'application/json'
    },
    success: function (res) {
        console.log(res.data)
    }
});

In this code, uni.request is a method for sending requests. It needs to pass in an object containing parameters such as url, data, header, success, etc., where url represents the request address, data represents the requested data, and header Represents the request header, and success represents the callback function after the request is successful. During the request process, you can also pass in the fail and complete parameters, which respectively represent the request failure and the callback function after the request ends.

Another way to send a request is to use the encapsulated uni.request method and encapsulate it into a separate JS file.

//request.js
import { getBaseUrl } from './config';

const req = (url, method, data) => {
    return new Promise((resolve, reject) => {
        uni.request({
            url: getBaseUrl() + url,
            method,
            data,
            header: {
                'content-type': 'application/json'
            },
            success: (res) => {
                resolve(res)
            },
            fail: (err) => {
                reject(err);
            }
        });
    });
}

export const post = (url, data) => {
    return req(url, 'POST', data);
}

export const get = (url, data) => {
    return req(url, 'GET', data);
}

In this code, a req method is encapsulated, passing in three parameters: url, method, and data, and returning a Promise object. Asynchronous operations are implemented through the Promise object, and the results of successful and failed requests are passed to resolve and reject methods. At the same time, the get and post methods are also encapsulated, which represent sending get and post requests respectively. The usage is as follows:

import { get, post } from './request';

get('/user', {id: 1}).then(res => {
    console.log(res.data);
});

post('/login', {username: 'example', password: 'example'}).then(res => {
    console.log(res.data);
});

2. Processing of request results

Uniapp The request result is generally a JSON object, as shown below:

{
    "code": 200,
    "message": "success",
    "data": {
        "username": "example",
        "age": 18
    }
}

Among them, code represents the status code, message represents the message, and data represents the request result data.

When processing the request result, you first need to determine whether the request is successful based on the code, and handle it accordingly based on different status codes. It can be processed in the success callback function of the request method or in the encapsulated method.

import { get } from './request';

get('/user', {id: 1}).then(res => {
    if(res.code === 200) {
        console.log(res.data);
    } else if(res.code === 401) {
        console.log('用户未登录');
    } else if(res.code === 404) {
        console.log('用户不存在');
    } else {
        console.log('请求失败');
    }
});

Another way to handle request results is to use interceptors. An interceptor is a function that can do some processing on the request before the request is sent or after the request response, such as adding tokens, filtering data, etc. The way to use interceptors in Uniapp is to encapsulate a request interceptor and a response interceptor to handle the pre-request and post-request logic respectively.

//request.js
import { getBaseUrl } from './config';

const requestInterceptors = (config) => {
    //添加token或其他逻辑
    return config;
}

const responseInterceptors = (response) => {
    const res = response.data;
    if(res.code === 200) {
        return res.data;
    } else {
        //根据code进行错误处理
        uni.showToast({
            title: res.message,
            icon: 'none'
        });
        return Promise.reject(res);
    }
}

const request = (options) => {
    const { url, method = 'GET', data } = options;
    const config = {
        url: getBaseUrl() + url,
        method,
        data,
        header: {
            'content-type': 'application/json'
        }
    }

    return new Promise((resolve, reject) => {
        uni.request({
            ...requestInterceptors(config),
            success: (response) => {
                if(response.statusCode == 200) {
                    resolve(responseInterceptors(response));
                } else {
                    reject(response)
                }
            },
            fail: (error) => {
                reject(error);
            }
        });
    })
}

export default request;

//config.js
export const getBaseUrl = () => {
    //返回请求地址
    return 'http://www.example.com';
}

In this code, requestInterceptors, responseInterceptors and request methods are encapsulated, and the request interceptor and response interceptor are encapsulated in them. The function of requestInterceptors and responseInterceptors is to process the request before and after the request respectively. The request method is a method for sending requests. The usage method is as follows:

import request from './request';

request({
    url: '/user',
    method: 'get',
    data: {id: 1}
}).then(res => {
    console.log(res);
}).catch(err => {
    console.log(err);
});

The final product code is the optimized code:

//config.js
export const getBaseUrl = () => {
    //返回请求地址
    return 'http://www.example.com';
}

//request.js
import { getBaseUrl } from './config';

const requestInterceptors = (config) => {
    //添加token或其他逻辑
    return config;
}

const responseInterceptors = (response) => {
    const res = response.data;
    if(res.code === 200) {
        return res.data;
    } else {
        //根据code进行错误处理
        uni.showToast({
            title: res.message,
            icon: 'none'
        });
        return Promise.reject(res);
    }
}

const request = (options) => {
    const { url, method = 'GET', data } = options;
    const config = {
        url: getBaseUrl() + url,
        method,
        data,
        header: {
            'content-type': 'application/json'
        }
    }

    return new Promise((resolve, reject) => {
        uni.request({
            ...requestInterceptors(config),
            success: (response) => {
                if(response.statusCode == 200) {
                    resolve(responseInterceptors(response));
                } else {
                    reject(response)
                }
            },
            fail: (error) => {
                reject(error);
            }
        });
    })
}

export default request;

//api.js
import request from './request';

export const getUser = (id) => {
    return request({
        url: '/user',
        method: 'get',
        data: {id}
    });
}

//页面中使用
import { getUser } from './api';

getUser(1).then(res => {
    console.log(res);
}).catch(err => {
    console.log(err);
});

This article introduces the relevant knowledge of requests and processing results in Uniapp. Includes different ways of sending requests and processing request results, as well as using interceptors for pre- and post-processing of requests. For developers who use Uniapp for cross-platform application development, mastering this knowledge will help improve development efficiency and code quality, and improve application stability and user experience.

The above is the detailed content of Detailed introduction to the relevant knowledge of requests and processing results in Uniapp. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
How do you debug issues on different platforms (e.g., mobile, web)?How do you debug issues on different platforms (e.g., mobile, web)?Mar 27, 2025 pm 05:07 PM

The article discusses debugging strategies for mobile and web platforms, highlighting tools like Android Studio, Xcode, and Chrome DevTools, and techniques for consistent results across OS and performance optimization.

What debugging tools are available for UniApp development?What debugging tools are available for UniApp development?Mar 27, 2025 pm 05:05 PM

The article discusses debugging tools and best practices for UniApp development, focusing on tools like HBuilderX, WeChat Developer Tools, and Chrome DevTools.

How do you perform end-to-end testing for UniApp applications?How do you perform end-to-end testing for UniApp applications?Mar 27, 2025 pm 05:04 PM

The article discusses end-to-end testing for UniApp applications across multiple platforms. It covers defining test scenarios, choosing tools like Appium and Cypress, setting up environments, writing and running tests, analyzing results, and integrat

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

What are some common performance anti-patterns in UniApp?What are some common performance anti-patterns in UniApp?Mar 27, 2025 pm 04:58 PM

The article discusses common performance anti-patterns in UniApp development, such as excessive global data use and inefficient data binding, and offers strategies to identify and mitigate these issues for better app performance.

How can you use profiling tools to identify performance bottlenecks in UniApp?How can you use profiling tools to identify performance bottlenecks in UniApp?Mar 27, 2025 pm 04:57 PM

The article discusses using profiling tools to identify and resolve performance bottlenecks in UniApp, focusing on setup, data analysis, and optimization.

How can you optimize network requests in UniApp?How can you optimize network requests in UniApp?Mar 27, 2025 pm 04:52 PM

The article discusses strategies for optimizing network requests in UniApp, focusing on reducing latency, implementing caching, and using monitoring tools to enhance application performance.

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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools