angular-cli中axios請求攔截、響應(yīng)攔截的配置

第一步:

npm 安裝axios,文件根目錄下安裝,指令如下

npm install axios --save  //安裝到生產(chǎn)環(huán)境

第二步:

配置 \color{red}{config.js } 文件,它是整個項目的統(tǒng)一配置文件,方便我們管理項目
在angular-cli項目的\color{red}{src/ } 文件夾下新建一個文件夾為 \color{red}{plugins } ,然后在 plugins/ 下新建 config.js 文件,寫入如下代碼

// 測試域名
// const testDomin = '' // 使用代理
const testDomin = 'http://172.20.1.26:8082'
// const testDomin = 'http://172.20.1.148:8082'
 
// 正式域名
const formalDomain = 'http://39.96.91.52/back'
 
// 環(huán)境變量
const env = process.env.NODE_ENV
const origin = env === 'development' ? testDomin : formalDomain
 
// config
const config = {
  // 版本號
  version: '0.1.1',
 
  // 域名
  domain: origin,
 
}
 
/**
 * 假日表
 * @param [month, day, type, name] type : 1 公歷 2 農(nóng)歷
 */
 
const legalHoliday = [
  ['01', '01', 1, '元旦'],
  ['01', '01', 2, '春節(jié)'],
  ['04', '05', 1, '清明節(jié)'],
  ['05', '01', 1, '勞動節(jié)'],
  ['05', '05', 2, '端午節(jié)'],
  ['08', '15', 2, '中秋節(jié)'],
  ['10', '01', 1, '國慶節(jié)']
]
 
// 數(shù)據(jù)字典分類
const dicCode = {
  goodsCategory: '1001', // 商品分類
  Brand: '1002', // 品牌
  category: '1003', // 類別
  doorType: '1004', // 門架種類
  tonnage: '1005' // 噸位
}
 
export {
  config,
  legalHoliday,
  dicCode
}

第三步:

如何封裝插件
首先,在angular-cli項目的 src/ 文件夾下新建一個文件夾為 plugins,然后在 plugins/ 下新建 axios.js文件,寫入如下代碼

import axios from 'axios'
import { config } from './config'
 
// 定義加載動畫
// let loading = null
// let loadingShow = false
 
// axios.defaults.baseURL = 'http://172.20.1.148:8082'
 
// 添加請求攔截器
axios.interceptors.request.use(
  conf => {
    // 配置axios請求的url  ${config.ajaxUrl} 是配置的請求url統(tǒng)一前綴,配置好就不用重復(fù)寫一樣的url前綴了,只寫后面不同的就可以了
    conf.url = `${config.domain}${conf.url}`
 
    // 顯示加載動畫
    // if (!loadingShow) {
    //   loadingShow = true
    //   loading = message.loading('數(shù)據(jù)加載中...', 0)
    // }
 
    // 設(shè)置 token 判斷是否存在token,如果存在的話,則每個http header都加上token
    // if (sessionStorage.getItem('auth')) {
    //   conf.headers['Authorize'] = sessionStorage.getItem('auth')
    // }
 
    return conf
  },
  error => {
    // 拋出請求錯誤信息
    Promise.reject(error.response)
  }
)
 
// 添加響應(yīng)攔截器
axios.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    // 請求失敗處理
    return Promise.reject(error)
  }
)
 
export default axios

第四步:

在組件中使用axios


image.png
import { Component, OnInit } from '@angular/core'
// 引入 Router
import {
  ActivatedRoute,
  Router,
  ActivatedRouteSnapshot,
  RouterState,
  RouterStateSnapshot
} from '@angular/router'
 
import axios from '../../plugins/axios'
 
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.sass']
})
export class LoginComponent implements OnInit {
  // 注冊 Router
  constructor(public router: Router) {}
 
  ngOnInit() {
    this.allList()
  }
 
  allList() {
    axios.get(`/back/common/getVerifyCode`).then(res => {})
  }
}

第五步:

重啟項目,查看效果


image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容