import Vue from 'vue' import axios from 'axios' import SystemConfiguration from './SystemConfiguration.js'; let baseURL = SystemConfiguration.constant const service = axios.create({ withCredentials: false, //表示跨域请求时是否需要使用凭证 crossDomain: true, // baseURL, timeout: 160000 }) // request请求拦截器,在请求之前做一些处理 service.interceptors.request.use( config => { console.log(config) uni.showLoading({ title: 'loading', mask: true }) console.log('============================') // if (config.urlType=='eth') { // config.url = config.url // } else { // config.url = baseURL.serverUrl + config.url // } config.baseURL = baseURL.serverUrl config.url = config.url // if (token) { // // config.headers['Authori-zation'] = token // config.headers['Authorization'] = token // } // console.log(config) // if (store.state.token) { // // 给请求头添加user-token // config.headers["user-token"] = store.state.token; // } return config; }, error => { console.log(error); // for debug return Promise.reject(error); } ); // 配置成功后的响应拦截器 service.interceptors.response.use(res => { uni.hideLoading() console.log(res) if (res.status == 200) { return res.data } else { return Promise.reject(res.msg); } }, error => { // if (error.response.status) { // switch (error.response.status) { // case 401: // break; // default: // break; // } // } return Promise.reject(error) }) // 在main.js中放入这段自定义适配器的代码,就可以实现uniapp的app和小程序开发中能使用axios进行跨域网络请求,并支持携带cookie axios.defaults.adapter = function(config) { //自己定义个适配器,用来适配uniapp的语法 return new Promise((resolve, reject) => { console.log(config, '我请求的',config) var settle = require('axios/lib/core/settle'); var buildURL = require('axios/lib/helpers/buildURL'); uni.request({ method: config.method.toUpperCase(), url: config.baseURL + '/' + buildURL(config.url, config.params, config .paramsSerializer), header: config.headers, data: config.data, dataType: config.dataType, responseType: config.responseType, sslVerify: config.sslVerify, complete: function complete(response) { //console.log("执行完成:",config.baseURL+'/' + buildURL(config.url, config.params, config.paramsSerializer),response.data) response = { data: response.data, status: response.statusCode, errMsg: response.errMsg, header: response.header, config: config }; settle(resolve, reject, response); }, fail: res => { uni.hideLoading() uni.showToast({ title: res, icon: 'none', duration: 1500 }) } }) }) } export default service