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

What should I do if uniapp cannot request using axios?

coldplay.xixi
Release: 2023-01-13 00:44:29
Original
5287 people have browsed it

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

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

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;// 重新请求时间间隔
Copy after login

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

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

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

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

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

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!

Related labels:
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!