Vue——封装axios请求,请求头携带token、cookie,当请求超时再次发送请求

utils/request.js

import axios from "axios";
const instance = axios.create({
     
  timeout: 8000,//设置网络请求超时时间
  headers: {
     
    "Content-Type": "application/x-www-form-urlencoded",  //设置传输的数据格式为form data的形式(a=1&b=2),默认是json的形式进行传输的({a:1,b:2})
    "common":{
     
		"CSRFToken"="token"//全局配置请求头携带token    CSRFToken这个字段是后端告诉你的  token的值是由后端返回的
	}
  },
  withCredentials:true,//全局设置请求头默认携带cookie
  retry: 3 /* 设置请求失败之后重新请求次数 */,
  retryInterval: 10000 /* 设置请求失败之后再次发起请求的间隔 */
});

//设置当数据请求失败的时候再次发起网路请求
instance.interceptors.response.use(undefined, function axiosRetryInterceptor(
  err
) {
     
  var config = err.config;
  // If config does not exist or the retry option is not set, reject
  if (!config || !config.retry) return Promise.reject(err);

  // Set the variable for keeping track of the retry count
  config.__retryCount = config.__retryCount || 0;

  // Check if we've maxed out the total number of retries
  if (config.__retryCount >= config.retry) {
     
    // Reject with the error
    return Promise.reject(err);
  }

  // Increase the retry count
  config.__retryCount += 1;

  // Create new promise to handle exponential backoff
  var backoff = new Promise(function(resolve) {
     
    setTimeout(function() {
     
      resolve();
    }, config.retryDelay || 1);
  });

  // Return the promise in which recalls axios to retry the request
  return backoff.then(function() {
     
    return axios(config);
  });
});

const baseURL = "/api";

export function get(url,config) {
     
  return instance.get(baseURL + url,config);
}

export function post(url, data,config) {
     
  return instance.post(baseURL + url, data,config);
}

/services/api.js

import {
      get, post } from "../utils/request";

export function login(data,config) {
     
  return post("/url/", data,config);
}

export function isLogin(config) {
     
  return get("/url/",config);
}
export function getData(data,config) {
     
const {
     name} = data;
  return get("/url/?name="+name,config);
}

在组件中进行调用

import {
      login,getData } from "@/services/API";
mounted(){
     
	login("username=admin&password=111",{
     
          headers: {
     
            common: {
      "CSRFToken": "token" }
          },
          withCredentials:true
        }).then(res=>{
     console.log(res)}).catch(err=>{
     console.log(err)});//给单个请求设置请求头携带cookie和token
	getData ({
     name:111}).then(res=>{
     console.log(res)}).catch(err=>{
     console.log(err)})
}

你可能感兴趣的:(Vue,vue,前端)