基于SpringCloud+vue(ElementUI)+mySQL前后端分离设计之--前端Fetch请求封装

hungzz 2019-06-28

开发一个博客系统

文章数:菜单文章都没更新完
搭建eureka注册中心 (请先阅读此文章) https://segmentfault.com/a/11...
搭建Beans编写Token解析注解 https://segmentfault.com/a/11...
搭建权限管理系统 https://segmentfault.com/a/11...
搭建后台管理系统 https://segmentfault.com/a/11...
前端Fetch请求封装 https://segmentfault.com/a/11...

搭建Vue项目,不多说网上搜

目录结构:

基于SpringCloud+vue(ElementUI)+mySQL前后端分离设计之--前端Fetch请求封装

HTTP.js 在这里我没有考虑浏览器不支持Fetch的情况
export default(type = '', url = '',data = {},parameter = {},headers = {},api = 'fetch') =>{
  const default_headers = {
    'Access-Control-Allow-Origin':'*',
    'Access-Control-Allow-Credentials':'true',
    'Accept-Charset':'utf-8'
  };

  if(!headers){
    headers = default_headers;
  }

  if (parameter) {
    let parameter_str = ''; //数据拼接字符串
    for (var key of parameter.keys()) {
      parameter_str += key + '=' + parameter.get(key) + '&';
    }
    if (parameter_str !== '') {
      parameter_str = parameter_str.substr(0, parameter_str.lastIndexOf('&'));
      url = url + '?' + parameter_str;
    }
  }

  let requestConfig = {
    method:type,
    headers:headers,
    mode:'cors',
    cache:'default',
    credentials:'include'
  }

  if(data){
    Object.defineProperty(requestConfig, 'body', {
      value: data
    });
  }

  return fetch(url, requestConfig);
}
verify.js 权限过滤部分
import router from '../router'
import http from '../tools/HTTP'
import { Message } from 'element-ui';
export default(type, url,data,parameter = {},headers = {}) => {
  //这里写获取访问url的权并进行接下来的操作(是否请求数据)
    return http(type, url, data,parameter, headers,'fetch');
}

api.js 封装前端要使用的请求

import verify from '../api/verify'
//import router from '../router'
import Constant from '../tools/Constant'//我的工具类
import VueCookies from 'vue-cookies'
var token = VueCookies.get(Constant.CookiesNames.ACCESS_TOKEN);
//token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MzY3MTk0MTMsInVzZXJJZCI6ImFkbWluIiwiaWF0IjoxNTM2MzczODEzfQ.eXns9N5fZBFiOfEeqSF5tU31QqrC20YSsNfeAtKRifU";
const default_headers = {
  'Accept':'application/json',
  'Access-Control-Allow-Origin':'*',
  'Access-Control-Allow-Credentials':'true',
  'Accept-Charset':'utf-8',
  'Content-Type': 'application/json',
  'at':token
};

var address = "http://127.0.0.1:8762";

var api={};
api.uploadFile=(data)=>verify('POST',address+'/api/matter',data,null,default_headers);
api.createProject=(data)=>verify('POST',address+'/api/set/project',data,null,default_headers);
api.getProject=(data)=>verify('GET',address+'/api/get/project',null,data,default_headers);
api.getProjects=(data)=>verify('GET',address+'/api/get/projects',data,null,default_headers);

api.login=(data)=>verify('POST',address+'/auth/login',data,null,default_headers);
api.verify=(data)=>('GET',address+'/auth/verify',data,null,default_headers);//检查是否有权限
export default api;

使用api

get请求:
      var get_project_form = new FormData();
      get_project_form.append(Constant.ParameterNames.PKID, 1);
      api.getProject(get_project_form).then((response) => response.json())
        .then((data) => {
          this.itemProject = data.data;
        });
post请求:
        var add_project_form = new FormData();
        add_project_form.append("projectName", this.projectForm.projectName);
        add_project_form.append("projectTag", this.projectForm.projectTag);//list
        add_project_form.append("projectTechnology", this.projectForm.projectTechnology);//list
        //注意:add_project_form工具自己的情况得到要提交的数据
        //convert_FormData_to_json工具类
        api.createProject(tool.convert_FormData_to_json(add_project_form)).then((response) => response.json())
          .then((data) => {
            console.log(data.data);
            Message({
              dangerouslyUseHTMLString: true,
              message: "<strong>创建项目</strong><br><strong>创建成功</i></strong>",
              iconClass:'el-icon-document'
            });
          });

相关推荐