当前位置:   article > 正文

vue3+ts axios封装及使用_vue3 类型“axiosresponse”上不存在属性“result”

vue3 类型“axiosresponse”上不存在属性“result”

http.ts文件

  1. import axios, { Axios, AxiosResponse, AxiosRequestConfig } from "axios";
  2. // 处理 类型“AxiosResponse<any, any>”上不存在属性“errorinfo”。ts(2339) 关键一步。
  3. declare module "axios" {
  4. interface AxiosResponse<T = any> {//参数与res的字段相对应
  5. result: T;
  6. statuscode: number;
  7. reason: string
  8. }
  9. export function create(config?: AxiosRequestConfig): AxiosInstance;
  10. }
  11. // 创建axios实例
  12. const request = axios.create({
  13. baseURL: '',// 所有的请求地址前缀部分(没有后端请求不用写)
  14. timeout: 10000, // 请求超时时间(毫秒)
  15. withCredentials: true,// 异步请求携带cookie
  16. headers: {
  17. // 设置后端需要的传参类型
  18. 'Content-Type': 'application/json'
  19. // 'token': x-auth-token',//一开始就要token
  20. // 'X-Requested-With': 'XMLHttpRequest',
  21. },
  22. })
  23. // request拦截器
  24. request.interceptors.request.use(
  25. config => {
  26. // 如果你要去localStor获取token
  27. // let token = localStorage.getItem("x-auth-token");
  28. // if (token) {
  29. // config.headers = {"x-auth-token": token}
  30. // }
  31. return config
  32. },
  33. error => {
  34. // 对请求错误做些什么
  35. Promise.reject(error)
  36. }
  37. )
  38. // response 拦截器
  39. request.interceptors.response.use(
  40. response => {
  41. // 对响应数据做点什么
  42. return response.data
  43. },
  44. error => {
  45. // 对响应错误做点什么
  46. return Promise.reject(error)
  47. }
  48. )
  49. export default request

接口文件.ts

  1. import instance from "./http";
  2. export const List = (data: any) =>
  3. instance.post("路径", data);

vue文件中的使用

  1. const getdata = () => {
  2. state.value.metaModel.page = 1
  3. state.value.loading = true;
  4. metaModelList(state.value.metaModel).then((res) => {
  5. console.log(res);
  6. state.value.listData = res.result.result
  7. console.log(state.value.listData)
  8. });
  9. }

代理vue.config.js

  1. module.exports = {
  2. outputDir: "dist", //build输出目录
  3. assetsDir: "assets", //静态资源目录(js, css, img)
  4. lintOnSave: false, //是否开启eslint
  5. devServer: {
  6. open: true, //是否自动弹出浏览器页面
  7. host: "localhost",
  8. port: "8080",
  9. https: false, //是否使用https协议
  10. proxy: {
  11. "/api": {
  12. target: "", //API服务器的地址
  13. changeOrigin: true, // 虚拟的站点需要更管origin
  14. pathRewrite: {
  15. //重写路径
  16. "^/api": "/api",
  17. },
  18. },
  19. },
  20. },
  21. };

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/285685
推荐阅读
相关标签
  

闽ICP备14008679号