天天看点

一个初级前端的简单http请求配置

HTTP请求封装与axios简易封装

以下文章基于 vue+element UI

一、配置vue config.js 跨域

module.exports = {
  devServer: {
    proxy: {
      "/api": {
        target: "http://192.168.110.29:8081/", //服务器 也就是前端请求地址
        changeOrigun: true, //是否跨域
        pathRewrite: {
          "^/api": "" //表示需要rewrite 重写的
        }
      }
    }
  }
};

           

二、配置 公用 http地址

  1. 在public文件夹下建立 global.js文件, 将我们的请求api地址 放在这里, 原因:我们在打包项目时不会对public文件夹进行打包所以即使项目上线也可以更改请求地址, 为了方便服务器更换或IP地址更换时修改
    var publicConfig = {
      hostConfig: {
        system: "http://192.168.110.29:8081/system/user/v1.0/test/",
      }
    };
    //存本地
    localStorage.setItem("publicConfig", JSON.stringify(publicConfig));
    
               
  2. 在public文件夹 indx.html文件 引入 global.js文件 不然该js运行不起来

三、在项目中获取公共的http地址,配置请求 api地址

  1. 在src目录建立config文件夹,然后建立 apiConfig.js文件
    // 取出 public 文件夹内 app.global.js 内存的本地 配置
    const publicConfig = JSON.parse(localStorage.publicConfig);
    /* 配置API接口应用访问地址 */
    const apiConfig = {
      system: {
        getUserList: publicConfig.hostConfig.system + "getUserList", //配置请求后半段 接口
      }
    };
    export default apiConfig;
    
               

四、封装简单的axios请求 因为我们的请求 基本都是改请求地址和参数 因此我们可以吧常用的 post get put del封装起来,同时做统一的请求错误处理方式

  1. 在src目录config文件夹下,建立 RequestConfig.js文件
    import axios from "axios";  //引入axios 请求
    import { Message } from "element-ui";  // 引入element 消息组件 做全局请求提示
    /**
     * * @param {*}  url //请求的地址     字符串类型  String
     * * @param {*}  data //请求的参数    对象类型   Object
     * * @param {*}  method //请求的方式  字符类型   String
     */
    export const post = async (url = "", data = {}, method = "post") => {
                              //这里暴露的post方法即post请求方法, method默认值也是post 在调用时我们一般传递 url 和 data参数即可
      let res = await axios(url, {
        data: data,
        method: method
      });
      if (res) {
        return res;
      } else {
       Message({
          showClose: true,
          message: "请求失败",
          type: "error"
        });
        return false;
      }
    };
    //get 请求
    /**
     * * @param {*}  url
     * * @param {*}  params
     * * @param {*}  method
     */
    export const get = async (url = "", params = {}, method = "get") => {
      let res = await axios(url, {
        params: params,
        method: method
      });
      if (res) {
        return res;
      } else {
        Message({
          showClose: true,
          message: "请求失败",
          type: "error"
        });
        return false;
      }
    };
    
               

五、使用以上的配置,发送一条简单的请求

  1. 在src目录建立api文件夹,然后建立 api.js文件
    import apiConfig from "../config/apiConfig";  //引入配置好的请求地址  每新增一个借口需到该文件新增一个对象 键和值
    import { post, get } from "../config/RequestConfig"; //引入已经封装的 简易请求
    
    //测试请求
    //暴露一个 请求方法给 页面使用 getUserList
    export const getUserList = () => {
      //返回请求方法的 结果,请求方法中已经有 异步 这里只需要返回结果即可
      //return调用的就是 封装的请求方法,参数根据自己需要填写, 这示例的请求无参数 只有url 且用的post方法 不需要在传 method
      return post(apiConfig.system.getUserList);
    };
    
               

六、在页面中使用请求方法

  1. 在我们的Vue页面中 引入请求方法
  2. 在生命周期或其他需要的时候调用引入的方法
    mounted() {
        this.initPage();
      },
      methods: {
        initPage() {
          getUserList().then(res => {
            if (res) {
              console.log("getUserListres", res.data.data);
            }
          });
        },
      }      
               
  3. 请求成功则返回数据
    一个初级前端的简单http请求配置
  4. 请求失败在页面弹出请求失败
    一个初级前端的简单http请求配置

继续阅读