欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

vue axios封裝httpjs,接口公用配置攔截操作

 更新時間:2020年08月11日 15:56:53   作者:csl125  
這篇文章主要介紹了vue axios封裝httpjs,接口公用配置攔截操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

做一下記錄,在vue項(xiàng)目中配置公用的請求https,

(1) 位置,在src中新建 src/utils/http.js

import axios from 'axios' // 引用axios
import { MessageBox, Message } from 'element-ui'
import Qs from 'qs' //引入數(shù)據(jù)格式化
import router from '@/router'
 
// axios 配置
axios.defaults.timeout = 50000 //設(shè)置接口響應(yīng)時間
// axios.defaults.baseURL = 'https://easy-mock.com/mock/' // 這是調(diào)用數(shù)據(jù)接口,公共接口url+調(diào)用接口名
let httpUrl = window.location.host
if (httpUrl.indexOf('.com') !== -1) {
 console.log('生產(chǎn)環(huán)境', httpUrl)
} else if (httpUrl.indexOf('.net') !== -1) {
 console.log('測試環(huán)境', httpUrl)
 axios.defaults.baseURL = 'http://www.test.com' // 這是調(diào)用數(shù)據(jù)接口,公共接口url+調(diào)用接口名
} else if (httpUrl.indexOf('localhost:8088') !== -1) {
 console.log('指定開發(fā)環(huán)境', httpUrl)
 axios.defaults.baseURL = 'http://localhost:8088/'
} else {
 console.log('開發(fā)環(huán)境', httpUrl)
 axios.defaults.baseURL = 'http://192.168.6.138:8080/' // 這是調(diào)用數(shù)據(jù)接口,公共接口url+調(diào)用接口名
}
 
// http request 攔截器,通過這個,我們就可以把Cookie傳到后臺
axios.interceptors.request.use(
 config => {
  if (config.method == "post") {
  // console.log('請求路徑', config.url)
  if (config.url === '/b/login/checkLogin') {
   config.headers = {
    'Content-Type': 'application/x-www-form-urlencoded' // 設(shè)置跨域頭部
   }
   config.data = Qs.stringify(config.data)
  } else if (config.url === '/b/carModel/createCarModelVersion') {
   // 此處設(shè)置文件上傳,配置單獨(dú)請求頭
   config.headers = {
    'Content-Type': 'multipart/form-data'
   }
  } else {
   let userInfo = localStorage.getItem('userInfo')
   if (userInfo === null) {
    return null
   }
   let bToken = localStorage.getItem('btoken')
   if (bToken === null) {
   } else {
    config.data.vwToken = bToken
   }
   config.headers = {
    'Content-Type': 'application/x-www-form-urlencoded' // 設(shè)置跨域頭部
   }
   config.data = Qs.stringify(config.data)
  }
}else{
console.log("get請求")
}
  return config
 },
 err => {
  return Promise.reject(err)
 }
)
 
// http response 攔截器
axios.interceptors.response.use(
 response => {
  // console.log('請求攔截返回參數(shù)', response)
  if (response.status === 200) {
   // 成功
   let returnCode = response.data.code
   if (returnCode > 10000 && returnCode < 20000) {
    // console.log('成功', response)
    Message.success(response.data.msg)
   } else if (returnCode >= 20000 && returnCode < 30000) {
    // 只彈窗,不操作
    // console.log('失敗1', response)
    Message.error(response.data.msg)
   } else if (returnCode >= 30000 && returnCode < 40000) {
    // 只彈窗,點(diǎn)擊跳到登入頁
    localStorage.removeItem('userInfo')
 
    MessageBox.confirm(response.data.msg, '確定登出', {
     confirmButtonText: '重新登錄',
     cancelButtonText: '取消',
     type: 'warning'
    }).then(() => {
     // console.log('此處應(yīng)退出登錄 重新實(shí)例化')
     router.push({ path: '/login' })
    })
   }
  }
  return response
 },
 error => {
  // console.log('error', error.toString())
  if (
   error.toString().trim() ===
   "TypeError: Cannot read property 'cancelToken' of null"
  ) {
   localStorage.removeItem('userInfo')
   MessageBox.confirm(
    '會話憑證失效,可以取消繼續(xù)留在該頁面,或者重新登錄',
    '確定登出',
    {
     confirmButtonText: '重新登錄',
     cancelButtonText: '取消',
     type: 'warning'
    }
   ).then(() => {
    // console.log('此處應(yīng)退出登錄 重新實(shí)例化')
    router.push({ path: '/login' })
   })
  }
 
  // console.log(error.toString().trim())
  if (error.toString().trim() === 'Error: Network Error') {
   MessageBox.alert('網(wǎng)絡(luò)請求異常,請稍后重試', '出錯了', {
    confirmButtonText: '確定',
    callback: action => {}
   })
  }
  return Promise.reject(error.response.data)
 }
)
 
export default axios
 
/**
 * fetch 請求方法
 * @param url
 * @param params
 * @returns {Promise}
 */
export function get(url, params = {}) {
 return new Promise((resolve, reject) => {
  axios
   .get(url, {
    params: params
   })
   .then(response => {
    resolve(response.data)
   })
   .catch(err => {
    reject(err)
   })
 })
}
 
/**
 * post 請求方法
 * @param url
 * @param data
 * @returns {Promise}
 */
export function post(url, data = {}) {
 return new Promise((resolve, reject) => {
  axios.post(url, data).then(
   response => {
    // console.log(response.data.code)
    resolve(response.data)
   },
   err => {
    reject(err)
   }
  )
 })
}
 
/**
 * patch 方法封裝
 * @param url
 * @param data
 * @returns {Promise}
 */
export function patch(url, data = {}) {
 return new Promise((resolve, reject) => {
  axios.patch(url, data).then(
   response => {
    resolve(response.data)
   },
   err => {
    reject(err)
   }
  )
 })
}
 
/**
 * put 方法封裝
 * @param url
 * @param data
 * @returns {Promise}
 */
export function put(url, data = {}) {
 return new Promise((resolve, reject) => {
  axios.put(url, data).then(
   response => {
    resolve(response.data)
   },
   err => {
    reject(err)
   }
  )
 })
}

(2) 在main.js中引入調(diào)用,定義全局

import axios from 'axios'
import { post, get, patch, put } from './utils/http'
 
// 將axios添加到原型鏈上
Vue.prototype.$axios = axios
 
// 定義全局變量
Vue.prototype.$post = post
Vue.prototype.$get = get
Vue.prototype.$patch = patch
Vue.prototype.$put = put

(3)在需要用到的.vue頁面直接使用

//this.logForm 為傳參
 
this.logForm = { id: this.selectId, knowledgeVersionId: this.baseValue }
this.$post('你的url', this.logForm).then(req => {
    this.logList = req.data
    this.logList.allCount = req.allCount
    this.logList.nowPage = req.nowPage
    this.logList.pageSize = req.pageSize
    this.loading = false
   }).catch(err => {
    console.log(err)
   })
 
 this.$post('/b/checkConfig/updateRelateKnowledge', { id: this.selectId, knowledgeVersionId: this.baseValue }).then(req => {
    console.log(req)
    if (req.code === 10000) {
     // this.options = req.data
     this.getConfigList()
    }
   }).catch(err => {
    console.log(err)
   })

補(bǔ)充知識:Vue項(xiàng)目關(guān)于axios的二次封裝service

一、安裝axios:npm i axios --save

二、在src目錄下新建文件service.js

三、在service.js文件中寫入以下代碼

import axios from 'axios'

// 創(chuàng)建一個擁有通用配置的axios實(shí)例,實(shí)例中的配置內(nèi)容根據(jù)實(shí)際開發(fā)需求而定
export const service = axios.create({
 baseURL: 'http://***.***.*.**:8080/', // 測試環(huán)境
 timeout: 1000 * 10, // 請求超時的毫秒數(shù),如果請求花費(fèi)超過timeout的時間,請求將被中斷
 withCredentials: true, // 表示跨域請求時是否需要使用憑證,默認(rèn)fasle
 headers: { 'Cache-Control': 'no-cache' } // 不允許緩存,需要重新獲取請求
})

// 添加請求攔截器
service.interceptors.request.use(config => {
 // 在發(fā)送請求之前做些什么
 return config
}, error => {
 // 對請求錯誤做些什么
 return Promise.reject(error)
})

// 添加響應(yīng)攔截器
axios.interceptors.response.use(response => {
 // 對響應(yīng)數(shù)據(jù)做點(diǎn)什么
 return response
}, error => {
 // 對響應(yīng)錯誤做點(diǎn)什么
 return Promise.reject(error)
})

以上是對axios的初步封裝,具體功能根據(jù)實(shí)際需求在service.js文件中進(jìn)行配置

四、全局使用使用service(也可以局部使用,稍后會說明局部使用方法)

第一步:在main.js中進(jìn)行掛載

import { service } from './service'

Vue.prototype.service = service

第二步:使用

// 注意:這里必須要使用async 和 await ,不然請求狀態(tài)一直是Promise {<pending>},拿不到請求數(shù)據(jù)
 async created () {
  let data = await this.service.get('menu/user/tree')
  console.log(data) //此時能拿到請求的數(shù)據(jù)
 }

五、局部使用service,在組件內(nèi)先引入再使用

<script>
import { service } from '../service'
export default {
 name: 'HelloWorld',
 data () {
  return {
   msg: 'sds'
  }
 },
 async created () {
  let data = await service.get('menu/user/tree')
  console.log(data)
 }
}
</script>

以上這篇vue axios封裝httpjs,接口公用配置攔截操作就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • vue-cli3 熱更新配置操作

    vue-cli3 熱更新配置操作

    這篇文章主要介紹了vue-cli3 熱更新配置操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-09-09
  • vue格式化element表格中的時間為指定格式

    vue格式化element表格中的時間為指定格式

    這篇文章主要介紹了vue中格式化element表格中的時間為指定格式,需要的朋友可以參考下
    2022-05-05
  • vue使用video插件vue-video-player詳解

    vue使用video插件vue-video-player詳解

    這篇文章主要為大家詳細(xì)介紹了vue使用video插件vue-video-player,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2020-10-10
  • Nuxt的路由動畫效果案例

    Nuxt的路由動畫效果案例

    這篇文章主要介紹了Nuxt的路由動畫效果案例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-11-11
  • VUE3安裝element?ui失敗的原因以及解決辦法

    VUE3安裝element?ui失敗的原因以及解決辦法

    這篇文章主要給大家介紹了關(guān)于VUE3安裝element?ui失敗的原因以及解決的相關(guān)資料,很多朋友升級使用Vue3了,但在安裝element?ui失敗出錯了,這里給大家總結(jié)下,需要的朋友可以參考下
    2023-09-09
  • VUE+elementui組件在table-cell單元格中繪制微型echarts圖

    VUE+elementui組件在table-cell單元格中繪制微型echarts圖

    這篇文章主要介紹了VUE+elementui組件在table-cell單元格中繪制微型echarts圖,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-04-04
  • vue3的基本使用方法詳細(xì)教程

    vue3的基本使用方法詳細(xì)教程

    這篇文章主要介紹了vue3的基本使用方法,結(jié)合實(shí)例形式詳細(xì)分析了vue3功能、組件、生命周期、TypeScript結(jié)合運(yùn)用等相關(guān)概念與使用方法,需要的朋友可以參考下
    2023-06-06
  • vue組件的路由高亮問題解決方法

    vue組件的路由高亮問題解決方法

    這篇文章主要給大家介紹了關(guān)于vue組件的路由高亮問題的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-05-05
  • Vue中util的工具函數(shù)實(shí)例詳解

    Vue中util的工具函數(shù)實(shí)例詳解

    本文通過實(shí)例代碼給大家介紹了Vue中util的工具函數(shù),代碼簡單易懂,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下
    2019-07-07
  • vue中 this.$set的使用詳解

    vue中 this.$set的使用詳解

    這篇文章主要為大家介紹了vue中 this.$set的使用,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助
    2021-11-11

最新評論