search
HomeWeb Front-enduni-appWhat 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.

What should I do if uniapp cannot request using axios?

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!

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

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)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools