vue项目对axios的全局配置


标准的vue-cli项目结构(httpConfig文件夹自己建的):

api.js:

//const apiUrl = 'http://test';//测试域名,自己改成自己的
 const apiUrl = 'http://xxoo';//线上域名,自己改成自己的 

export default apiUrl

http.js:

/**
 * ajax请求配置
 */
import axios from 'axios'
import apiURL from './api.js'
//import Qs from 'qs'

import cookie from '../../static/js/cookie.js'

// axios默认配置
axios.defaults.timeout = 10000;   // 超时时间
axios.defaults.baseURL = apiURL;  // 默认地址

//整理数据
axios.defaults.transformRequest = function (data) {
//data = Qs.stringify(data);
data = JSON.stringify(data);
  return data;
};

// 路由请求拦截
// http request 拦截器
axios.interceptors.request.use(
  config => {
    //config.data = JSON.stringify(config.data);  
    config.headers['Content-Type'] = 'application/json;charset=UTF-8';
    //判断是否存在ticket,如果存在的话,则每个http header都加上ticket
    if (cookie.get("token")) {
        //用户每次操作,都将cookie设置成2小时
        cookie.set("token",cookie.get("token") ,1/12)    
        cookie.set("name",cookie.get("name") ,1/12)
     config.headers.token = cookie.get("token");
     config.headers.name= cookie.get("name");
 } return config; }, error => { return Promise.reject(error.response); }); // 路由响应拦截 // http response 拦截器
axios.interceptors.response.use( response => { if (response.data.resultCode=="404") { console.log("response.data.resultCode是404") // 返回 错误代码-1 清除ticket信息并跳转到登录页面 // cookie.del("ticket") // window.location.href='http://login.com'
        return }else{ return response; } }, error => { return Promise.reject(error.response)   // 返回接口返回的错误信息
 }); export default axios;

main.js

import axios from './httpConfig/http'
Vue.prototype.$http = axios

请求示例:

//post
this
.$http.post('/itemProps/addItemProps',{   name: this.name,   parentId:this.parentId,   sortOrder:0 }).then((res)=>{
  console.log(res) }).
catch((err)=>{ alert("请求失败") })
//get
this.$http.get("/roles/getPersonnelInfoRoles",{
  params:{
    key:"value"
  }
}).then((res) => {
  console.log(res)
}).catch((err)=>{
  alert("请求失败")
})

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM