Home Web Front-end uni-app Detailed introduction to the relevant knowledge of requests and processing results in Uniapp

Detailed introduction to the relevant knowledge of requests and processing results in Uniapp

Apr 27, 2023 am 09:06 AM

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)
    }
});
Copy after login

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);
}
Copy after login

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);
});
Copy after login

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
    }
}
Copy after login

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('请求失败');
    }
});
Copy after login

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';
}
Copy after login

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);
});
Copy after login

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);
});
Copy after login

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 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 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)

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

How can you use lazy loading to improve performance? How can you use lazy loading to improve performance? Mar 27, 2025 pm 04:47 PM

Lazy loading defers non-critical resources to improve site performance, reducing load times and data usage. Key practices include prioritizing critical content and using efficient APIs.

What are some common patterns for managing complex data structures in UniApp? What are some common patterns for managing complex data structures in UniApp? Mar 25, 2025 pm 02:31 PM

The article discusses managing complex data structures in UniApp, focusing on patterns like Singleton, Observer, Factory, and State, and strategies for handling data state changes using Vuex and Vue 3 Composition API.

How does UniApp handle global configuration and styling? How does UniApp handle global configuration and styling? Mar 25, 2025 pm 02:20 PM

UniApp manages global configuration via manifest.json and styling through app.vue or app.scss, using uni.scss for variables and mixins. Best practices include using SCSS, modular styles, and responsive design.

What are computed properties in UniApp? How are they used? What are computed properties in UniApp? How are they used? Mar 25, 2025 pm 02:23 PM

UniApp's computed properties, derived from Vue.js, enhance development by providing reactive, reusable, and optimized data handling. They automatically update when dependencies change, offering performance benefits and simplifying state management co

See all articles