登录  /  注册
博主信息
博文 67
粉丝 0
评论 2
访问量 68051
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
VUE axios的安装和使用及封装
搁浅
原创
335人浏览过

axios请求方式

  1. axios.get(config)
  2. axios.post(config)
  3. axios.request(config)
  4. axios.head(config)
  5. axios.put(config)
  6. axios.patch(config)
  7. axios.delete(config)

npm i axios -S 安装axios

使用axios

  1. <template>
  2. <button @click="axi()">axios</button>
  3. </template>
  4. <script setup>
  5. import axios from "axios";//引入axios
  6. function axi(){
  7. axios({
  8. url:'https://api.baidu.cn/api/index',
  9. method:'get',
  10. params:{
  11. page:1,
  12. }
  13. }).then(res=>{
  14. console.log(res)
  15. })
  16. }
  17. </script>

路径src/network/axios.js

  1. import axios from "axios"
  2. import router from '../router'
  3. import {Toast} from "vant";
  4. // 创建实例时设置配置的默认值
  5. const service = axios.create({
  6. timeout: 10000,// 超时时间
  7. // baseURL: 'http://apis.juhe.cn',//默认请求URl
  8. headers: 'application/x-www-form-urlencoded;charset=UTF-8',
  9. });
  10. // 请求拦截器,在发送请求之前做些什么
  11. service.interceptors.request.use((config) => {
  12. // 如果API需要认证, 在这统一设置
  13. const token = window.localStorage.getItem('token');
  14. if (token) {
  15. config.headers.Authorization = 'Bearer ' + token;
  16. }
  17. // config.headers['token']='' //没有登陆界面时,可以不携带token
  18. return config;
  19. }, error => {
  20. // 对请求错误做些什么
  21. return Promise.reject(error);
  22. });
  23. // 响应拦截器
  24. service.interceptors.response.use((response) => {
  25. // 对响应数据做点什么
  26. // 如果返回的状态码为200,说明接口请求成功,可以正常拿到数据,否则的话抛出错误
  27. if (response.status === 200) {
  28. return Promise.resolve(response);
  29. } else {
  30. return Promise.reject(response);
  31. }
  32. }, error => {
  33. // 对响应错误做点什么
  34. switch (error.response.status) {
  35. // 401: 未登录
  36. // 未登录则跳转登录页面,并携带当前页面的路径
  37. // 在登录成功后返回当前页面,这一步需要在登录页操作。
  38. case 401:
  39. router.replace({
  40. path: '/login',
  41. query: {
  42. redirect: router.currentRoute.fullPath
  43. }
  44. });
  45. break;
  46. // 403 token过期
  47. // 登录过期对用户进行提示
  48. // 清除本地token和清空vuex中token对象
  49. // 跳转登录页面
  50. case 403:
  51. Toast({
  52. duration: 2000,
  53. message: '登录过期,请重新登录'
  54. });
  55. // 清除token
  56. sessionStorage.removeItem('token');
  57. // 跳转登录页面,并将要浏览的页面fullPath传过去,登录成功后跳转需要访问的页面
  58. setTimeout(() => {
  59. router.replace({
  60. path: '/login',
  61. query: {
  62. redirect: router.currentRoute.fullPath
  63. }
  64. });
  65. }, 1000);
  66. break;
  67. // 404请求不存在
  68. case 404:
  69. Toast({
  70. duration: 3000,
  71. message: '网络请求不存在'
  72. });
  73. break;
  74. // 其他错误,直接抛出错误提示
  75. default:
  76. Toast({
  77. duration: 4000,
  78. message: error.response.data.message
  79. });
  80. }
  81. return Promise.reject(error.response);
  82. });
  83. export default service;

路径src/network/request.js

  1. // 导入封装好的axios实例
  2. import service from './axios';
  3. const isProduction=process.env.NODE_ENV === 'production'//是否生产环境
  4. const httpList = {
  5. test:{ // 测试环境
  6. http1:'http://localhost:8080', // ip1
  7. http2:'ws://197.82.15.15:8082', // ip2
  8. },
  9. production: { // 生产环境
  10. http1:'http://192.168.3.44',// ip1
  11. http2:'ws://197.82.15.15:8084', // ip2
  12. }
  13. };
  14. let baseUrl;
  15. if (isProduction) { // 是否生产环境
  16. baseUrl = httpList['production'];
  17. }else{
  18. baseUrl = httpList['test'];
  19. }
  20. const request = {
  21. /**
  22. * methods: 请求
  23. * @param url 请求地址
  24. * @param params 请求参数
  25. */
  26. get(url,params,httpType='http1'){
  27. const config = {
  28. method: 'get',
  29. url:baseUrl[httpType]+url
  30. };
  31. if(params) config.params = params;
  32. return service(config)
  33. },
  34. post(url,params,httpType='http1'){
  35. const config = {
  36. method: 'post',
  37. url:baseUrl[httpType]+url
  38. };
  39. if(params) config.data = params;
  40. return service(config)
  41. },
  42. put(url,params,httpType='http1'){
  43. const config = {
  44. method: 'put',
  45. url:baseUrl[httpType]+url
  46. };
  47. if(params) config.params = params;
  48. return service(config)
  49. },
  50. delete(url,params,httpType='http1'){
  51. const config = {
  52. method: 'delete',
  53. url:baseUrl[httpType]+url
  54. };
  55. if(params) config.params = params;
  56. return service(config)
  57. },
  58. video:`${baseUrl.http1}/video`,//视频地址
  59. image:`${baseUrl.http1}/image`//图片地址
  60. };
  61. export default request;

挂载到全局

  1. import { createApp } from 'vue'
  2. import App from './App.vue'
  3. import './registerServiceWorker'
  4. import router from './router'
  5. import store from './store'
  6. import request from './network/request'
  7. import 'element-plus/dist/index.css'
  8. const app = createApp(App)
  9. app.use(store).use(router).use(ElementPlus).mount('#app')
  10. app.config.globalProperties.$request = request;//挂载搞组合式全局
  11. window.request=request//挂载到window

使用

  1. <script setup>
  2. import {getCurrentInstance} from 'vue'
  3. const {proxy} = getCurrentInstance()
  4. function axi(){
  5. proxy.$request.get('/api/simpleWeather/query'{page:1})
  6. }
  7. </script>
本博文版权归博主所有,转载请注明地址!如有侵权、违法,请联系admin@php.cn举报处理!
全部评论 文明上网理性发言,请遵守新闻评论服务协议
0条评论
作者最新博文
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号

  • 登录PHP中文网,和优秀的人一起学习!
    全站2000+教程免费学