Home > Web Front-end > uni-app > body text

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

PHPz
Release: 2023-04-27 10:32:29
Original
2830 people have browsed it

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!

source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template