Blogger Information
Blog 67
fans 0
comment 2
visits 72050
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
VUE axios的安装和使用及封装
搁浅
Original
376 people have browsed it

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>
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post