vue封裝http請求

vue中http請求的基本封裝,分爲一下兩個文件,可以在基本配種中自定義使用

1. 封裝http請求(http.js)

import axios from "axios";
import { Toast } from "mint-ui";
var HttpRequest = {
  getRequest({ url, data = {}, method = "GET" }) {
    return new Promise((resolve, reject) => {
      this._getRequest(url, resolve, reject, data, method);
    });
  },
  _getRequest: function(url, resolve, reject, data = {}, method = "GET") {
    let format = method.toLocaleLowerCase() ==='get'?'params':'data';
    axios({
      url: url,
      method: method,
      [format]: data,
      header: {
        "content-type": "application/json"
      }
    }).then(res => {
      if (res.code == 0) {
        resolve(res);
      } else if (res.code == -1) {
        resolve(res);
      }
    }).catch(() => {
      reject();
      Toast({
        message: "發生錯誤,請檢查!",
        position: "middle",
        duration: 2000
      });
    })
  }
};
export { HttpRequest };

2.封裝API方法(httpUtil.js)

import { HttpRequest } from "./http.js";
let http = {
  // POST請求
  GetUserItem: function() {
    return HttpRequest.getRequest({
      method: "POST",
      url: "http://localhost:8081/index",
      
    });
  },
  // GET請求
  getUserAll: function() {
    return HttpRequest.getRequest({
      method: "GET",
      url: "http://localhost:8081/index",
    //   data: datas
    });
  }
};
export { http };

3.使用

import { http } from "../api/httpUitl.js";


     http.GetUserItem().then(res => {
             console.log(res)
         });
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章