vue 封装axios请求(基础版)

  1. 新建页面,封装axios请求;
import axios from "axios";

//创建axios实例
var service = axios.create({
   
   
  baseURL: "后端接口地址前缀",
  timeout: 5000,
  withCredentials: true,
  headers: {
   
   
    "content-type": "application/json",
  },
});
export default {
   
   
  service,

  //get请求
  get(url, data) {
   
   
    return service({
   
   
      url: url,
      method: "get",
      query: data,
    });
  },

  //post请求
  post(url, data) {
   
   
    return service({
   
   
      url: url,
      method: "post",
      data: data,
    });
  },
};

  1. main.js引用封装的请求;
import http from "@/api/http.js"; //axios实例化后引入取名http
Vue.prototype.$http = http; //放入全局
  1. 页面使用请求
 this.$http.get("后端接口地址前缀的拼接",{
   
   data: 1,array: []}).then((res) => {
   
   });
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章