日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

axios 最全 请求拦截器 响应拦截器 配置公共请求头 超时时间 以及get delete post put 四种请求传参方式

發布時間:2023/12/31 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 axios 最全 请求拦截器 响应拦截器 配置公共请求头 超时时间 以及get delete post put 四种请求传参方式 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

axios 攔截器

  • 請求攔截器
    • 請求攔截器的作用是在請求發送前進行一些操作
      • 例如在每個請求體里加上token,統一做了處理如果以后要改也非常容易
  • 響應攔截器
    • 響應攔截器的作用是在接收到響應后進行一些操作
      • 例如在服務器返回登錄狀態失效,需要重新登錄的時候,跳轉到登錄頁
# 1. 請求攔截器 axios.interceptors.request.use(function(config) {console.log(config.url)# 1.1 任何請求都會經過這一步 在發送請求之前做些什么 config.headers.mytoken = 'nihao';# 1.2 這里一定要return 否則配置不成功 return config;}, function(err){#1.3 對請求錯誤做點什么 console.log(err)})#2. 響應攔截器 axios.interceptors.response.use(function(res) {#2.1 在接收響應做些什么 var data = res.data;return data;}, function(err){#2.2 對響應錯誤做點什么 console.log(err)})

axios 全局配置

# 配置公共的請求頭 axios.defaults.baseURL = 'https://api.example.com'; # 配置 超時時間 axios.defaults.timeout = 2500; # 配置公共的請求頭 axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; # 配置公共的 post 的 Content-Type axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

**

axios基礎用法

  • get和 delete請求傳遞參數
    • 通過傳統的url 以 ? 的形式傳遞參數
    • restful 形式傳遞參數
    • 通過params 形式傳遞參數
  • post 和 put 請求傳遞參數
    • 通過選項傳遞參數
    • 通過 URLSearchParams 傳遞參數
# 1. 發送get 請求 axios.get('http://localhost:3000/adata').then(function(ret){ # 拿到 ret 是一個對象 所有的對象都存在 ret 的data 屬性里面// 注意data屬性是固定的用法,用于獲取后臺的實際數據// console.log(ret.data)console.log(ret)})# 2. get 請求傳遞參數# 2.1 通過傳統的url 以 ? 的形式傳遞參數axios.get('http://localhost:3000/axios?id=123').then(function(ret){console.log(ret.data)})# 2.2 restful 形式傳遞參數 axios.get('http://localhost:3000/axios/123').then(function(ret){console.log(ret.data)})# 2.3 通過params 形式傳遞參數 axios.get('http://localhost:3000/axios', {params: {id: 789}}).then(function(ret){console.log(ret.data)})#3 axios delete 請求傳參 傳參的形式和 get 請求一樣axios.delete('http://localhost:3000/axios', {params: {id: 111}}).then(function(ret){console.log(ret.data)})# 4 axios 的 post 請求# 4.1 通過選項傳遞參數axios.post('http://localhost:3000/axios', {uname: 'lisi',pwd: 123}).then(function(ret){console.log(ret.data)})# 4.2 通過 URLSearchParams 傳遞參數 var params = new URLSearchParams();params.append('uname', 'zhangsan');params.append('pwd', '111');axios.post('http://localhost:3000/axios', params).then(function(ret){console.log(ret.data)})#5 axios put 請求傳參 和 post 請求一樣 axios.put('http://localhost:3000/axios/123', {uname: 'lisi',pwd: 123}).then(function(ret){console.log(ret.data)})

**

總結

以上是生活随笔為你收集整理的axios 最全 请求拦截器 响应拦截器 配置公共请求头 超时时间 以及get delete post put 四种请求传参方式的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。