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) => {
    
    });

猜你喜欢

转载自blog.csdn.net/jiaodeqiangs/article/details/111477010