axios
本文最后更新于322 天前,其中的信息可能已经过时,如有错误请发送邮件到3368129372@qq.com

记录一下axios,用法来源于官网

官网

https://axios-http.com/docs/api_intro
http://axios-js.com/

用法

定义myAxios

目录结构为:
plugins
|_____myAxios.js

创建实例

// Set config defaults when creating the instance
const myAxios = axios.create({
    baseURL: 'https://localhost:8080/api'
});

cookie

每次向后端发送请求时携带cookie

myAxios.defaults.withCredentials = true;

创建请求与响应拦截器

// 添加请求拦截器
myAxios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    console.log("请求拦截,",config)
    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});

// 添加响应拦截器
myAxios.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    console.log("响应拦截",response)
    return response;
}, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
});

记得导入与导出

import axios from "axios";

……

export default myAxios;

使用示例

下面为页面加载时显示get请求获取到的所有user

onMounted(async () => {
  const userListData = await myAxios.get('/user/search/tags',{
    params: {
      tags: tags,
    },
    paramsSerializer: params => {
      return qs.stringify(params, { indices: false })
    }
  }).then(function (response) {
    console.log("请求tags成功",response);
    showToast('成功')
    console.log("response为:", response);
    return response.data?.data;
  }).catch(function (error){
    console.log("请求tags失败",error)
    showToast('失败')
  })
  if(userListData){
    userList.value = userListData;
  }
})

额外用法

  1. 请求数据为List类型
    使用第三方库'qs'

    import qs from 'qs';

    在传递的params之下,添加paramsSerializer属性

    paramsSerializer: params => {
        return qs.stringify(params, { indices: false })
    }
感谢您的收看~
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇