123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205 |
- import Vue from 'vue'
- import '../static/encry.min.js' //接口加密工具
- import hostObj from './apiConfig.js' //打包路径
- /**
- * @param baseUrl 服务信息(如:/landcrm)
- * @param url 服务器接口地址,以'/'开头
- * @param method HTTP请求方法(GET/POST)
- * @param reference 服务地址后的传参,数组形式
- * @param data 请求的参数
- * @param dataType 请求参数的传参类型(FORMDATA/JSON/XML)
- * @param mFetch 接口是否是fetch请求(true/false)
- */
- export default async (baseUrl = '', url = '', method = 'GET', reference = [], data = {}, dataType = 'FORMDATA', mFetch = true) => {
- if (process.env.NODE_ENV == 'production') {
- // url = hostObj[baseUrl] + url;
- if (baseUrl) {
- // baseUrl = hostObj[baseUrl];
- baseUrl = process.env.URL + baseUrl;
- }
- }
- url = baseUrl + url;
- if (reference && reference.length > 0) {
- url += "/" + reference.join("/");
- }
- method = method.toUpperCase();
- //格式化data参数
- if (data && typeof data == "object") {
- data = JSON.parse(JSON.stringify(data));
- }
- if (method == 'GET') {
- let dataStr = ''; //数据拼接字符串
- Object.keys(data).forEach(key => {
- if (typeof (data[key]) == "undefined") {
- data[key] = "";
- }
- dataStr += key + '=' + encodeURIComponent(data[key]) + '&';
- })
- if (dataStr !== '') {
- dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
- url = url + '?' + dataStr + '&_t=' + new Date().getTime();
- } else {
- url = url + '?_t=' + new Date().getTime();
- }
- }
- if (window.fetch && mFetch) {
- var header_content = {};
- if (dataType && dataType === "XML") {
- header_content = {
- 'Accept': 'application/xml',
- 'Content-Type': 'application/x-www-form-urlencoded'
- };
- } else if (dataType && dataType === "FORMDATA") {
- header_content = {
- 'Accept': 'application/json',
- 'Content-Type': 'application/x-www-form-urlencoded'
- };
- } else if (dataType && dataType === "JSON") {
- header_content = {
- 'Accept': 'application/json',
- 'Content-Type': 'application/json'
- };
- }
- header_content.platform = 'web';
- header_content.sign = key_gen.encode(key_gen.handlerData(method == 'GET' ? url.substring(url.indexOf("?") + 1) : data));
- if (localStorage.token && localStorage.token != "") {
- header_content.token = localStorage.token;
- }
- if (localStorage.user_id && localStorage.user_id != "") {
- header_content.userId = localStorage.user_id;
- }
- let requestConfig = {
- credentials: 'include',
- method: method,
- headers: header_content,
- mode: "cors",
- cache: "force-cache"
- }
- if (method == 'POST') {
- if (dataType === "FORMDATA") {
- Object.defineProperty(requestConfig, 'body', {
- value: initData(data)
- })
- } else if (dataType === "JSON") {
- Object.defineProperty(requestConfig, 'body', {
- value: JSON.stringify(data)
- })
- }
- }
- try {
- const response = await fetch(url, requestConfig);
- if (response.headers.get("token_code") == -2 || response.headers.get("token_code") == -1) {
- Vue.prototype.$Message.config({
- top: 80,
- duration: 3
- });
- Vue.prototype.$Message.info("当前账号已过期,请重新登录!");
- Vue.prototype.$Message = function (str) {
- return;
- }
- setTimeout(function () {
- localStorage.clear();
- location.reload();
- return "";
- }, 3000);
- } else {
- if (dataType && dataType === "XML") {
- const responseJson = await response.text();
- return responseJson
- } else {
- const responseJson = await response.json();
- return responseJson
- }
- }
- } catch (error) {
- Vue.prototype.$Spin.hide();
- const responseJson = {
- errCode: 500,
- msg: "系统异常"
- };
- return responseJson;
- // throw new Error(error)
- }
- } else {
- return new Promise((resolve, reject) => {
- let requestObj;
- if (window.XMLHttpRequest) {
- requestObj = new XMLHttpRequest();
- } else {
- requestObj = new ActiveXObject;
- }
- let sendData = '';
- if (method == 'POST') {
- if (dataType === "FORMDATA") {
- sendData = initData(data)
- } else if (dataType === "JSON") {
- sendData = JSON.stringify(data)
- }
- }
- requestObj.open(method, url, true);
- if (dataType && dataType === "XML") {
- requestObj.setRequestHeader("Accept", "application/xml");
- requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
- } else if (dataType && dataType === "FORMDATA") {
- requestObj.setRequestHeader("Accept", "application/json");
- requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
- } else if (dataType && dataType === "JSON") {
- requestObj.setRequestHeader("Accept", "application/json");
- requestObj.setRequestHeader("Content-type", "application/json");
- }
- requestObj.setRequestHeader("platform", 'web');
- requestObj.setRequestHeader("sign", key_gen.encode(key_gen.handlerData(method == 'GET' ? url.substring(url.indexOf("?") + 1) : data)));
- requestObj.setRequestHeader("token", localStorage.token || '');
- requestObj.setRequestHeader("userId", localStorage.user_id || '');
- requestObj.send(sendData);
- requestObj.onreadystatechange = () => {
- if (requestObj.readyState == 4) {
- if (requestObj.status == 200) {
- let obj = requestObj.response || requestObj.responseT
- if (typeof obj !== 'object' && obj.indexOf("<?xml") == -1) {
- if (obj.indexOf("<p>") === -1) {
- obj = JSON.parse(obj);
- } else {
- obj = String(obj);
- }
- }
- resolve(obj)
- }
- }
- }
- })
- }
- }
- function initData(params) {
- var URLSearchParams = require('url-search-params');
- //360浏览器不支持URLSearchParams
- if (typeof URLSearchParams === "function") {
- var formMap = new URLSearchParams();
- for (var key in params) {
- if (typeof (params[key]) == "undefined") {
- params[key] = '';
- }
- formMap.append(key, params[key]);
- }
- return formMap;
- } else {
- return params;
- }
- }
|