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.url) console.log(config) uni.showLoading({ title: 'loading', mask: true }) console.log('============================') if (config.url.indexOf('http')<-1) { config.url = config.url } else { config.url = baseURL.serverUrl + 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) { return new Promise((resolve, reject) => { config.url=config.baseURL+'/'+config.url var settle = require('axios/lib/core/settle'); var buildURL = require('axios/lib/helpers/buildURL'); uni.request({ method: config.method.toUpperCase(), url: 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) { response = { data: response.data, status: response.statusCode, errMsg: response.errMsg, header: response.header, config: config }; // console.log(response) settle(resolve, reject, response); } }) }) } export default service