亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Vue中axios攔截器如何單獨配置token

 更新時間:2019年12月27日 13:19:33   作者:就是不健身  
這篇文章主要介紹了Vue axios攔截器如何單獨配置token及vue axios攔截器的使用,需要的朋友可以參考下

在了解到cookie、session、token的作用后學習token的使用

cookie

cookie是隨著url將參數(shù)發(fā)送到后臺,安全性最低,并且大小受限,不超過4kb左右,它的數(shù)據(jù)保存在客戶端

session

session數(shù)據(jù)保存在服務端,在內(nèi)存中開辟空間存儲數(shù)據(jù),session文件名即sessionID保存在cookie內(nèi),隨cookie傳送到服務端后在服務端匹配session文件

token

token是服務端的一種算法,如果登錄成功,服務端就會根據(jù)算法生成一個字符串,將字符串傳遞回客戶端。這個字符串就是token,安全性最高

以上都有可能受到CSRF攻擊

axios攔截器會在發(fā)送請求前先進行處理,將token放進key中保存在請求頭中,這個key是前后臺約定好的。這樣配置好后,每次發(fā)送請求的時候,請求頭都會帶上token傳送到后臺進行校驗。

axios的特點(官網(wǎng))

  • 支持瀏覽器和node.js
  • 支持promise
  • 能攔截請求和響應
  • 能轉(zhuǎn)換請求和響應數(shù)據(jù)
  • 能取消請求
  • 自動轉(zhuǎn)換JSON數(shù)據(jù)
  • 瀏覽器端支持防止CSRF(跨站請求偽造)

方法一:我們在使用axios請求的時候可以先獲取我們已經(jīng)存入localStorage里的token

然后在攔截器里使用[…]進行拼接

import axios from 'axios';
import qs from 'qs';
axios.defaults.baseURL = process.env.VUE_APP_BASE_API;
let token = localStorage.getItem('token')
// Add a request interceptor
axios.interceptors.request.use(function (config) {
  // Do something before request is sent
  //console.log(config)
  if(config.method==='post'){
    config.data=qs.stringify({
      token:token,
      ...config.data
    })
  }else if(config.method==='get'){
    config.params={
      token:token,
      ...config.params
    }
  }
  return config;
 }, function (error) {
  // Do something with request error
  return Promise.reject(error);
 });

// Add a response interceptor
axios.interceptors.response.use(function (response) {
  // Do something with response data
  return response;
 }, function (error) {
  // Do something with response error
  return Promise.reject(error);
 });

 class http{
   static get(url,params){
     return axios.get(url,params)
   }
   static post(url,params){
    return axios.post(url,params)
  }
 }
 export default http;

方法二:

axios修改全局默認配置:

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

axios配置攔截器:

// 添加一個請求攔截器
axios.interceptors.request.use(function (config) {
  // Do something before request is sent
  return config;
  //這里經(jīng)常搭配token使用,將token值配置到tokenkey中,將tokenkey放在請求頭中
  config.headers['Authorization'] = token;
  
 }, function (error) {
  // Do something with request error
  return Promise.reject(error);
 });

// 添加一個響應攔截器
axios.interceptors.response.use(function (response) {
  // Do something with response data
  return response;
 }, function (error) {
  // Do something with response error
  return Promise.reject(error);
 });

這兩種方法就可以讓我們在axios攔截器里拼接token了,而不是每一個請求都需要加一個token值

總結(jié)

以上所述是小編給大家介紹的Vue中axios攔截器如何單獨配置token,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!

相關(guān)文章

最新評論