Y_Shmily

导航

vue3axios配置与简单封装

一,安装axios

npm install axios

 

 

二,配置axios请求

  1.在src目录下新建 request 目录

  2. request 目录下新建http.js请求

  3.配置请求头与常用请求方式封装

    

 1 import axios from "axios";
 2 import qs from "qs";
 3 
 4 // axios.defaults.baseURL = 'http://www.baidu.com/api/'  //正式
 5 axios.defaults.baseURL = "http://www.myapp.com/API/WebAPI/"; //测试
 6 
 7 //post请求头
 8 axios.defaults.headers.post["Content-Type"] =
 9   "application/x-www-form-urlencoded;charset=UTF-8";
10 //设置超时
11 axios.defaults.timeout = 10000;
12 
13 axios.interceptors.request.use(
14   (config) => {
15     return config;
16   },
17   (error) => {
18     return Promise.reject(error);
19   }
20 );
21 
22 axios.interceptors.response.use(
23   (response) => {
24     if (response.status == 200) {
25       return Promise.resolve(response);
26     } else {
27       return Promise.reject(response);
28     }
29   },
30   (error) => {
31     console.log("请求错误!" + error);
32   }
33 );
34 export default {
35   //导出post请求
36   post(url, data) {
37     return new Promise((resolve, reject) => {
38       axios({
39         method: "post",
40         url,
41         data: qs.stringify(data),
42       })
43         .then((res) => {
44           resolve(res);
45         })
46         .catch((err) => {
47           reject(err);
48         });
49     });
50   },
51   //导出get请求
52   get(url, data) {
53     return new Promise((resolve, reject) => {
54       axios({
55         method: "get",
56         url,
57         params: data,
58       })
59         .then((res) => {
60           resolve(res);
61         })
62         .catch((err) => {
63           reject(err);
64         });
65     });
66   },
67 };

  4.引用请求

  

import http from "../request/http";
  http
      .get("GetInfoByID", {
        ID: "666",
      })
      .then((res) => {
        console.log(res);
      });

4.1全局引用

修改main.js

import { createApp } from "vue";
import App from "./App.vue";
import router from "./router";
import store from "./store";
import http from "./request/http";

const app = createApp(App);
app.config.globalProperties.$http = http;
app.use(store).use(router).mount("#app");

调用

const _this = this;
    _this.$http
      .get("GetColumnByid", {
        Cid: "5",
      })
      .then((res) => {
        console.log(res);
      });

 

三.跨域问题解决(没有跨域问题直接忽略以下)

  叫后台去解决或者设置代理

  vue3处理方案

  在vue.config.js的module.exports里面添加

  

  devServer: {
    proxy: {
      "/api": {
        target: "http://www.myapp.com/API/WebAPI/",
        changeOrigin: true,
        pathRewrite: {
          "^/api": "",
        },
      },
    },
  },

http.js里面相应的链接也得改改了

axios.defaults.baseURL = "/api/"; //测试

差不多就是这样了

posted on 2021-10-13 11:29  Y_Shmily  阅读(798)  评论(0编辑  收藏  举报