vue -element admin 修改request,headers添加参数

1.方法一

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  headers: {
    ak: window.sessionStorage.getItem("code") || ""
  },
  transformRequest: [
    function(data, headers) {
      // `transformRequest` 允许在向服务器发送前,修改请求数据
      // 只能用在 'PUT', 'POST' 和 'PATCH' 这几个请求方法
      // 结合create_headers里的内容,在这里又新增一条信息sex=man
      // 因此network中查看的结果是:name=xiaoming&age=12&sex=man
      headers["ak"] = window.sessionStorage.getItem("code") || "";
      return JSON.stringify(data);
    }
  ],
  timeout: 10000 // request timeout
});

2.推荐方法

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent

    if (window.sessionStorage.getItem("code")) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers["ak"] = window.sessionStorage.getItem("code");
    }    
    return config;
  },
  error => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);
posted @ 2021-05-18 08:44  gggggggxin  阅读(2321)  评论(0编辑  收藏  举报