axios封装

axios封装

1、初始化环境
vue init webpack deaxios

npm install axios –S

cnpm install vuex -S

2、封装axios(创建 src/api 文件夹

	config\urls.js 配置全局url变量:
	export default {
 	// api请求地址
 	 // API_URL: 'http://mup.dev.yiducloud.cn/'
  	API_URL: 'http://1.1.1.3:8888'
	}
	
		src\api\ajax.js:
		import Axios from 'axios'
		import URLS from '../../config/urls'

//1、使用自定义配置新建一个 axios 实例
const instance = Axios.create({
  baseURL: URLS.API_URL,
  headers: {
    'Content-Type': 'application/json'
  }
});

//2、添加请求拦截器
instance.interceptors.request.use(
  config => {
    //发送请求前添加认证token
    config.headers.Authorization = sessionStorage.getItem('token')
    // console.log(sessionStorage.getItem('token'),11223344)
    return config
  },
  err => {
    return Promise.reject(err)
  });

//3、添加响应拦截器
instance.interceptors.response.use(function (response) {
  // 对响应数据处理
  if (response.status === 200 || response.status === 201 || response.status === 400) {
    const data = response.data
    if (data.code === 200 || data.code === 201) {
      return data
    }
  }
  return Promise.reject(response)
}, function (error) {
  if (error.response) {
    switch (error.response.status) {
      case 400:
        return Promise.reject(error.response.data)
      case 401:
        window.location.href = '/login'
    }
  }
  // const errorData = error.response.data
  // if (errorData.code === 400) {
  //   return Promise.reject(errorData.desc)
  // }
  // return Promise.reject(errorData)
})

// export const getNodegroups = params => { return instance.get(`${base}/nodegroup/v1/nodegroups/list/`, params).then(res => res.data) }
// export const getNodegroups = params => { return instance.get(`/nodegroup/v1/nodegroups/list/`, params).then(res => res) }
export default instance
	
	src\api\api.js:
	import URLS from '../../config/urls'
import ajax from './ajax'
let base = URLS.API_URL
// 用户相关
export const requestLogin = params => { return ajax.post(`${base}/users/v1/user/login/`, params).then(res => res) }
	
	src\api\index.js:
	import * as api from './api'
	export default api

3、使用vuexsrc\store\index.js
3.1

import Vue from 'vue'
import Vuex from 'vuex'
import login from './modules/login/login'
Vue.use(Vuex);
export default new Vuex.Store({
modules:{
	login
 }
});

3.2 src\store\modules\login\login.js:

import {
requestLogin,
} from '../../../api/api'  // 导入封装后的axios请求
const state = {}
const getters = {}
const actions = {
async loginMethod ({commit}, params) {
return requestLogin(params).then(response => 		response)
	},
};
const mutations = {}
export default {
  state,
  getters,
  actions,
  mutations
}

4、入口
4.1 main.js 导入store:

	// The Vue build version to load with the `import` 		command
	// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
	import Vue from 'vue'
	import App from './App'
	import router from './router'
	import store from './store/index'
	
	Vue.config.productionTip = false

	/* eslint-disable no-new */
	new Vue({
	  el: '#app',
	  router,
	  store,
	  components: { App },
	  template: '<App/>'
	})
	

4.2 App.vue 组件发送请求:

	<template>
    <div id="app">
	<p @click="handleLogin">点击发送axiso请求	</p>
	<router-view/>
	</div>
	</template>

	<script>
	import { mapActions } from 'vuex'
	export default {
	name: 'App',
	methods: {
		...mapActions(['loginMethod']),
		handleLogin () {
      	var loginParams = { username: 'zhangsan', 	password: '123456' }
      	this.loginMethod(loginParams).then(response => {
        // this.logining = false
        sessionStorage.setItem('token', response.data)
        // this.$router.push({ path: '/' })
      }).catch(error => {
        this.loading = false
        this.error(error.desc ? error.desc : '服务器异常')
      })
    }
},
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

在这里插入图片描述

5、封装axios作用
1.我们在此将此项目所用到的所有接口调用方法都做了定义,这样既方便查看也利于管理。
2. 我们需要调用接口方法的时候,我们只需要在对应vue文件中的标签里直接import想用的接口方法就行了    例如:import { getOptList,branchList,addOperator } from “…/…/api/index”;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值