vue项目之axios

配置axios发起登录请求

main.js中:配置axios

  1. 导入axios
  2. 配置请求的根路径
  3. axios包挂载到vue原型对象上:这样每一个vue组件都可以通过this直接访问到$http

从而去发起ajax请求

// 导入axios包
import axios from 'axios'
// 配置请求的根路径
axios.defaults.baseURL = 'http://127.0.0.1:8888/api/private/v1/'
Vue.prototype.$http = axios

通过axios请求拦截器为请求头添加token,保证拥有获取数据的权限

API接口文档要求:需要授权的API ,必须在请求头中使用 Authorization 字段提供 token 令牌

意思是:除了登录接口之外,其他所有接口必须授权才能正常调用,怎么授权呢?

​ 调用登录接口–服务器端会返回登录成功的token令牌,这个令牌就是我们权限认证的字段

​ 在每一个请求头中添加Authorization 字段提供 token 令牌,想到了请求拦截器!!!

main.js中:

请求拦截器内容,放下下面代码的前面

// 把axios包挂载到vue实例对象的属性上
Vue.prototype.$http = axios

登录成功之后,查看network-login,查看请求头 Authorization:null
原因:因为发起的是登录请求,你在登录期间服务器肯定没给你颁发令牌,默认是null
如果登录之后,调用其他接口,再去监听请求就会发现Authorization的值就是token值
这样服务器接收到这次请求,它会先判断Authorization是否符合要求,它才会给你响应。
如果不符合要求或者Authorization:null,服务器会驳回这次请求

只要通过axios向服务器端发送请求,必然会在发送请求期间优先调用use回调函数,会这次请求进行预处理
这次请求经过处理之后,才会发送到服务器进行真正的处理

axios请求拦截

config是请求对象

  axios.interceptors.request.use(config => {
    // 为请求头对象,添加 Token 验证的 Authorization 字段
    config.headers.Authorization = window.sessionStorage.getItem('token')
    // 表示对这次请求做了预处理
    return config  
  })

如何在全局使用 axios

有三种方法:

  1. 结合 vue-axios使用
    • 首先在主入口文件main.js中引用
import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(VueAxios,axios);
  • 之后就可以使用了,在组件文件中的methods里去使用了
getBanners(){
   this.axios.get('api/getBanners').then((response)=>{
     this.banners=response.data.data;
   }).catch((response)=>{
     console.log(response);
   })
}
  1. axios 改写为Vue 的原型属性(项目中的做法)
    • 首先在主入口文件main.js中引用,之后挂在vue的原型链上
Vue.prototype.$ajax= axios
  • 在组件中使用
getBanners(){
   this.$ajax.get('api/getBanners').then((response)=>{
     this.banners=response.data.data;
   }).catch((response)=>{
     console.log(response);
   })
}
  1. 结合 Vuex的action
    • vuex的仓库文件store.js中引用,使用action添加方法
import Vue from 'Vue'
import Vuex from 'vuex'

import axios from 'axios'

Vue.use(Vuex)
const store = new Vuex.Store({
// 定义状态
state: {
 user: {
   name: 'xiaoming'
 }
},
actions: {
 // 封装一个 ajax 方法
 login (context) {
   axios({
     method: 'post',
     url: '/user',
     data: context.state.user
   })
 }
}
})

export default store
  • 在组件中发送请求:this.$store.dispatch
this.$store.dispatch('login')

使用方法:

get请求用params传递参数

data中定义:

  • 请求参数对象queryinfo
  • 权限列表 rightslist
const {data: res} = await this.$http.get('users',{params:this.queryinfo}) 

if(res.meta.status!==200) return this.$message.error(res.meta.msg)

// 把获取到的权限数据保存到data数据中
this.rightslist = res.data
// 请求路径:categories/:id/attributes

const {data: res} = await this.$http.get(`categories/${this.cateId}/attributes`,{
	params: {sel: this.activeName}
})

if(res.meta.status!==200){
	return this.$message.error('获取参数列表失败!')
}
// 获取参数成功
console.log(res.data);
post请求 直接添加请求参数对象

请求路径:categories/:id/attributes

const {data: res} = await this.$http.post('categories',this.addCateForm)
const {data: res} = await this.$http.post(`categories/${this.cateId}/attributes`,{
	attr_name: this.addForm.attr_name,
	attr_sel: this.activeName
})
delete请求直接添加请求参数对象

请求路径: categories/:id/attributes/:attrid

const confirmResult = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示',{
	confirmButtonText: '确定',
	cancelButtonText: '取消',
	type: 'warning'
}).catch(err => err)
// 用户取消了删除的操作
if(confirmResult!=='confirm'){
	return this.$message.info('已取消删除!')
} 
// 删除的业务逻辑
const {data: res} = await
this.$http.delete(`categories/${this.cateId}/attributes/${attr_id}`)

if(res.meta.status!==200){
	return this.$message.error('删除参数失败!')
} 
this.$message.success('删除参数成功!')
put请求:直接添加请求参数对象

请求路径:categories/:id/attributes/:attrId

const {data: res} = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`,{
	attr_name: this.editForm.attr_name,
	attr_sel: this.activeName
})
if(res.meta.status!==200){
	return this.$message.error('修改参数失败!')
} 
// 1.修改参数成功
this.$message.success('修改参数成功!')
  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

落花流雨

你的鼓励将是我创作的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值