Vue使用axios发送请求并实现简单封装


一、安装axios

npm install axios --save

二、简单使用

1.配置

main.js中加入如下内容

// 引入axios ---------------------------------------------------
import axios from 'axios'
Vue.prototype.$axios = axios
Vue.prototype.$axios.defaults.baseURL = 'http://127.0.0.1:8000/' // 请求根路径
// -------------------------------------------------------------

2.发送请求

<1>get

this.$axios.get('index').then(res => {
  // 返回数据在 res.data 中
})

<2>post

this.$axios.post('login', {user:"admin", pwd:"123"}).then(res => {
   // 返回数据在 res.data 中
})

<3>并发

var res1 = this.$axios.get('index')
var res2 = this.$axios.post('login', {user:"admin", pwd:"123"})
this.$axios.all([res1, res2]).then(this.$axios.spread(res1, res2) => {
  // 两个请求的返回结果在 res1 和 res2 中
})

三、封装使用

1.创建js封装类

src/request/index.js

// 引入
import Axios from 'axios'
import { Message } from 'element-ui'   // 需要装个 element-ui,错误提示界面友好一些
import vue from '../main.js'

// // 前端存在 localStorage 中的 token
// const token = localStorage.getItem('token')

// 实例化
const request = Axios.create({
  // baseURL: "http://192.168.0.46:",  	// 服务根路径
  timeout: 200000,				// 请求过期时间
  // headers: {
  //   Authorization: token    	// token 插入请求头给后端校验
  // }
}) 


// 前端请求拦截器
request.interceptors.request.use(function (config) {
  // 发送请求的相关逻辑
  // config:对象  与 axios.defaults 相当
  // 借助 config 将 localStorage 中的 token 加入请求头
  let token = localStorage.getItem('token')
  // 判断token存在就加入请求头
  if (token) {
    config.headers.Authorization = token
  }
  
  // 这里也可以将一些反爬的加密信息加入请求头中的自定义字段中交由后端进行验证 ---------------
  // todo
  // ---------------------------------------------------------------------------------
  
  return config
}, function (error) {
  // Do something with request error
  return Promise.reject(error)
})


// 后端返回拦截器
request.interceptors.response.use(res => {
	// console.log(res)
  // 后端校验 token 剩余时间不足一半时,会返回一个新的token,和 208 状态码,当接收到 208 状态码时,更新 localStorage 中的 token
  if (res.status == 208) {
	  // console.log(res.headers)
	  // localStorage.removeItem('token')
	  console.log('状态续签!')
	  localStorage.setItem('token', res.headers.authorization)
    // Message.error("something err...")  // 返回错误的提示信息
  
  // 当后端校验 token 失败时,说明 token 过期或者 token 有误,此时后端返回状态码是 200(如果后端返回不是2XX的话不会走这个拦截器,所以状态码不能返回 401),但在数据中增加一个 code 字段,返回 401,当前端接收 到 code==401 时,删除 localStorage 中的 token,并重定向到登录页
  } else if (res.data.code == 401) {
	    Message.error("登录过期,请重新登录...")  // 返回错误的提示信息
	    localStorage.removeItem('token')
	    // localStorage.removeItem('nickname')
	    // Vue.prototype._router.push('login')
	    // console.log(vue.$router.push('login'))
	   
	    // Message.error('route',vue.$route.path);
	    vue.$router.push({name: 'login', params: {}})
	    // window.location.replace(globalUrl.login)
  
  // 
  } 
  
  return res.data     // 只取 res 中的 data,后续取值不需要再写一层 data 了  
})


// 导出
export default request

2.创建一个后端url配置类

src/config/index.js

// 定义全局变量【可以配置多个后端】
const rootUrl = 'http://192.168.3.1:8008' + '/qa_system_back'		
const gptChatRootUrl = 'http://192.168.3.1:9991' + '/gpt_chat'
const gptOtherRootUrl = 'http://192.168.3.1:9993' + '/gpt_other'

const globalUrl = {
	rootUrl: rootUrl,

	contactSelectByServer: rootUrl + '/contact/select_by_server',
	contactSelectByAdmin: rootUrl + '/contact/select_by_admin',
	login: rootUrl + '/admin/login',
	
	gptChatRootUrl: gptChatRootUrl,
	gptChatUrl: gptChatRootUrl + '/cxgpt/chat',
	
	gptOtherRootUrl: gptOtherRootUrl,
	gptFindHistoryChat: gptOtherRootUrl + '/cxgpt/history',
	gptPollingFindChat: gptOtherRootUrl + '/cxgpt/search_answer',
	
} 

export {
    globalUrl
}

3.配置

main.js 中改成如下内容

// 引入axios ---------------------------------------------------
import request from './request'
Vue.prototype.$http = request
// -------------------------------------------------------------

// 挂载全局变量 -----------------------------------
import { globalUrl, } from './config';
Vue.prototype.globalUrl = globalUrl
// ----------------------------------------------

4.发送请求

<1>get

this.$http.get(this.globalUrl.contactSelectByServer).then(res => {
  // 返回数据在 res.data 中
})

<2>post

this.$http.post(this.globalUrl.login, {user:"admin", pwd:"123"}).then(res => {
   // 返回数据在 res.data 中
})

<3>并发

var res1 = this.$http.get(this.globalUrl.gptOtherRootUrl)
var res2 = this.$http.post(this.globalUrl.login, {user:"admin", pwd:"123"})
this.$http.all([res1, res2]).then(this.$http.spread(res1, res2) => {
  // 两个请求的返回结果在 res1 和 res2 中
})
  • 7
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

什么都干的派森

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

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

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

打赏作者

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

抵扣说明:

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

余额充值