• Vue项目中对axios进行封装(模板)


    Axios,是一个基于promise  的网络请求库,作用于node.js和浏览器中,它是 isomorphic 的(即同一套代码可以运行在浏览器和node.js中)。在服务端它使用原生node.js http模块, 而在客户端 (浏览端) 则使用XMLHttpRequest。

    1 安装axios 

    npm install axios

    2 在项目的更目录创建一个 util文件,然后新建一个名为service.js 的文件

    (注意点baseURL 是接口路径,请求根据请求不同进行设置,这里使用到了element-plus框架)

    安装 element-plus框架

    npm install element-plus --save

    service.js文件代码如下

    1. import axios from "axios"
    2. import { ElLoading } from 'element-plus'
    3. import { ElMessage } from 'element-plus'
    4. // 使用create创建axios实例
    5. let loadingObj = null
    6. const Service = axios.create({
    7. timeout:8000,
    8. baseURL:"http:XXX",
    9. headers:{
    10. "Content-type":"application/json;charset=utf-8",
    11. }
    12. })
    13. // 请求拦截-增加loading,对请求做统一处理
    14. Service.interceptors.request.use(config=>{
    15. loadingObj=ElLoading.service({
    16. lock: true,
    17. text: 'Loading',
    18. background: 'rgba(0, 0, 0, 0.7)',
    19. })
    20. return config
    21. })
    22. // 响应拦截-对返回值做统一处理
    23. Service.interceptors.response.use(response=>{
    24. loadingObj.close()
    25. const data = response.data
    26. if(data.meta.status!=200 && data.meta.status!=201){
    27. ElMessage.error(data.meta.msg||"服务器出错")
    28. // 请求出错
    29. return data
    30. }
    31. return data
    32. },error=>{
    33. loadingObj.close()
    34. ElMessage({
    35. message:"服务器错误",
    36. type:"error",
    37. duration:2000
    38. })
    39. })
    40. // post请求
    41. export const post=config=>{
    42. return Service({
    43. ...config,
    44. method:"post",
    45. data:config.data
    46. })
    47. }
    48. // get请求
    49. export const get=config=>{
    50. return Service({
    51. ...config,
    52. method:"get",
    53. params:config.data
    54. })
    55. }
    56. // put请求
    57. export const put=config=>{
    58. return Service({
    59. ...config,
    60. method:"put",
    61. data:config.data
    62. })
    63. }// delete请求
    64. export const del=config=>{
    65. return Service({
    66. ...config,
    67. method:"delete"
    68. })
    69. }

    3 接口文件 新建一个request.js 文件放入util文件夹中

    1. import {post,get,put,del} from "./service"
    2. export const loginApi = function(data) {
    3. return post({
    4. url:"/login",
    5. data
    6. })
    7. }

    4 在具体页面使用中

  • 相关阅读:
    【树莓派不吃灰】命令篇⑤ ps -ef | grep xxx | grep -v grep | wc -l 命令
    golang的超时处理使用技巧
    sed 原地替换文件时遇到的趣事
    java 处理树形结构数据
    Opencv实现的三次样条曲线(Cubic Spline)插值
    编译cef114.2 with h264
    这些常见的python编码习惯,你都会吗
    LeetCode 1173.即时食物配送
    NASM汇编教程翻译01 第一讲 Hello, World!
    理解make/makefile/cmake/qmake和Makefile编写规则
  • 原文地址:https://blog.csdn.net/weixin_44948981/article/details/126143656