What should I do if uniapp cannot request using axios?
The solution to the problem that uniapp cannot request using axios: first create a new [axios.js] file in the root directory and configure a new axios in the file; then use this adapter and set the number of times to re-initiate requests and The time between each re-request.
The operating environment of this tutorial: windows7 system, uni-app2.5.1 version. This method is suitable for all brands of computers.
Recommended (free): uni-app development tutorial
Uniapp cannot use axios to solve the problem of request Method:
Create a new axios.js file in the root directory, and configure a new axios in the file
import axios from "axios"; const service = axios.create({ withCredentials: true, crossDomain: true, baseURL: '***', timeout: 6000 })
Create a lib folder in the root directory, and in this folder Create an adapter.js file in it, which configures the axios adaptation based on uniapp. Remember to throw this adapter
import settle from "axios/lib/core/settle" import buildURL from "axios/lib/helpers/buildURL" /* 格式化路径 */ const URLFormat = function (baseURL, url) { return url.startsWith("http") ? url : baseURL } /* axios适配器配置 */ const adapter = function (config) { return new Promise((resolve, reject) => { uni.request({ method: config.method.toUpperCase(), url: buildURL(URLFormat(config.baseURL, config.url), config.params, config.paramsSerializer), header: config.headers, data: config.data, dataType: config.dataType, responseType: config.responseType, sslVerify: config.sslVerify, complete: function complete(response) { response = { data: response.data, status: response.statusCode, errMsg: response.errMsg, header: response.header, config: config }; settle(resolve, reject, response); } }) }) } export default adapter;
In the axios.js file in the root directory, use this adapter and set the re-initiation request The number of times and the interval between each re-request
import adapter from "./lib/adapter" service.defaults.adapter = adapter; service.defaults.retry = 5; // 设置请求次数 service.defaults.retryDelay = 1000;// 重新请求时间间隔
Set an interceptor after the request is completed. If the status code in the response header is 200, it means success, and the data obtained by the request will be returned. Otherwise, it will be regarded as an error request. , need to return a Promise. Create an axiosError.js in the lib to handle failed requests.
service.interceptors.response.use(res => { if (res.status == 200) { return res; } else { return Promise.reject(res); } }, err => axiosError(err, service))
axiosError.js needs to pass in the error intercepted by the axios interceptor and the newly created axios. This error handling page only acts as a distributor. We can proceed based on the status in the response header. Handle the error. Unhandled errors are handled during use and return Promise.reject
// 处理401错误代码 import Error401 from "../handlers/401Error"; export default function (err, axios) { const errStatus = err.response.status; if (errStatus == 401) { return Error401(err); // 401没有权限,重新请求设置token } else { return Promise.reject(err); } }
to handle the 401 error code. When the request fails and the status code in the response header is 401, I do not have the authority to make the request. , which can be processed according to the project. We need to carry the token, so 401 means that the token is not carried or invalid. There is no need to pass in the token when requesting. Axios will automatically carry the token and make a request again when encountering 401. Create a handlers folder in the root directory, and create a 401Error.js in it to handle 401 errors.
Vuex is used here, and Vuex needs to be introduced, because the methods for obtaining tokens, setting tokens, and tokens are all placed in it! ! ! Use store.dispatch("getToken") to get the token and set the token to the request header Authorization
import interceptorsError from "../lib/interceptorsError"; import store from 'store/index' /* 需要传入axios错误配置 */ export default function (err, axios) { const config = err.config;// axios请求配置 store.dispatch("getToken").then(function () { config.headers["Authorization"] = store.state.cnrToken.cnr_token; }); err.config = config; return interceptorsError(axios, config); }
After everything is ready, you need to make a request again. Create an interceptorsError.js file in the root directory to re-execute the request. This method requires a request configuration, and we only need to pass in the configuration of our previous request.
export default function (axios, config) { // 如果配置不存在或未设置重试选项,reject if (!config || !config.retry) return Promise.reject(err); // 设置变量以跟踪重试计数 config.__retryCount = config.__retryCount || 0; // 如果重试次数大于最大重试次数,reject if (config.__retryCount >= config.retry) { return Promise.reject(err); } // 每重试一次记录一次重试次数 config.__retryCount += 1; // 重试间隔时间 const backoff = new Promise(function (resolve) { setTimeout(function () { resolve(); }, config.retryDelay || 1000); }); return backoff.then(function () { return axios(config); }); }
This is my code in Vuex
/* * @Author: UpYou * @Date: 2020-09-25 16:30:13 * @LastEditTime: 2020-09-25 21:32:56 * @Descripttion: token * */ const state = { cnr_token: '', POST_KEYS: { ...获取token需要的验证信息... } }; const mutations = { /* 设置token */ SET_CNRTOKEN(state, Payload) { if (Payload.startsWith("Bearer")) state.cnr_token = Payload; else state.cnr_token = "Bearer" + Payload; } } const actions = { /* 向服务器获取token */ getToken(context, args) { return new Promise(function (resolve, reject) { uni.request({ url: "token服务器地址", data: { ...context.state.POST_KEYS }, method: "get", async success(res) { await context.commit('SET_CNRTOKEN', res.data.access_token) await resolve(res.data) }, fail: reject }); }) } } export default { state, mutations, actions, }
The above is the detailed content of What should I do if uniapp cannot request using axios?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Steps to launch UniApp project preview in WebStorm: Install UniApp Development Tools plugin Connect to device settings WebSocket launch preview

Generally speaking, uni-app is better when complex native functions are needed; MUI is better when simple or highly customized interfaces are needed. In addition, uni-app has: 1. Vue.js/JavaScript support; 2. Rich native components/API; 3. Good ecosystem. The disadvantages are: 1. Performance issues; 2. Difficulty in customizing the interface. MUI has: 1. Material Design support; 2. High flexibility; 3. Extensive component/theme library. The disadvantages are: 1. CSS dependency; 2. Does not provide native components; 3. Small ecosystem.

UniApp has many conveniences as a cross-platform development framework, but its shortcomings are also obvious: performance is limited by the hybrid development mode, resulting in poor opening speed, page rendering, and interactive response. The ecosystem is imperfect and there are few components and libraries in specific fields, which limits creativity and the realization of complex functions. Compatibility issues on different platforms are prone to style differences and inconsistent API support. The security mechanism of WebView is different from native applications, which may reduce application security. Application releases and updates that support multiple platforms at the same time require multiple compilations and packages, increasing development and maintenance costs.

uniapp development requires the following foundations: front-end technology (HTML, CSS, JavaScript) mobile development knowledge (iOS and Android platforms) Node.js other foundations (version control tools, IDE, mobile development simulator or real machine debugging experience)

UniApp is based on Vue.js, and Flutter is based on Dart. Both support cross-platform development. UniApp provides rich components and easy development, but its performance is limited by WebView; Flutter uses a native rendering engine, which has excellent performance but is more difficult to develop. UniApp has an active Chinese community, and Flutter has a large and global community. UniApp is suitable for scenarios with rapid development and low performance requirements; Flutter is suitable for complex applications with high customization and high performance.

When choosing between UniApp and native development, you should consider development cost, performance, user experience, and flexibility. The advantages of UniApp are cross-platform development, rapid iteration, easy learning and built-in plug-ins, while native development is superior in performance, stability, native experience and scalability. Weigh the pros and cons based on specific project needs. UniApp is suitable for beginners, and native development is suitable for complex applications that pursue high performance and seamless experience.

Solve the problem of UniApp error: 'xxx' animation effect cannot be found UniApp is a cross-platform application development framework based on the Vue.js framework, which can be used to develop applications for multiple platforms such as WeChat applets, H5, and App. During the development process, we often use animation effects to improve user experience. However, sometimes you will encounter an error: The 'xxx' animation effect cannot be found. This error will cause the animation to fail to run normally, causing inconvenience to development. This article will introduce several ways to solve this problem.
