uniapp使用axios處理請求
阿新 • • 發佈:2020-10-08
uniapp可以使用原生的請求方式,uni.request(),但涉及到請求或者響應攔截 可能需要自己動手去寫,因此這裡使用axios去處理uniapp的網路請求
引入axios
npm install axios --save
建立axios例項
util/request.js
//封裝axios請求 import Vue from 'vue' import axios from 'axios' import store from '@/store' // console.log('token----------------------------->',store.state.token) // create an axios instance const service = axios.create({ // baseURL:'http://3333.com', // withCredentials: true, //允許跨域攜帶cookie // send cookies when cross-domain requests 注意:withCredentials和後端配置的cross跨域不可同時使用 timeout: 6000, // request timeout async: true, crossDomain: true }) // request攔截器,在請求之前做一些處理 service.interceptors.request.use( config => { if (store.state.token) { // 給請求頭新增user-token config.headers["Authorization"] = 'Bearer ' + store.state.token; } // console.log('請求攔截成功') //針對媒體型別資料進行特殊處理 if (config.method === 'formdata') { config.method = 'POST'; config.headers['Content-Type'] = 'multipart/form-data'; } // console.log('請求攔截器config------------------',config) return config; }, error => { // console.log('請求攔截器錯誤-------------', error); // for debug return Promise.reject(error); } ); //配置成功後的攔截器 service.interceptors.response.use(res => { // console.log('響應攔截器res---------------', res) //res.data.status== 200 if (res.data.code == 0 || res.data.code == 0) { return res.data } else { return Promise.reject(res.data.msg); } }, error => { // console.log('響應攔截器錯誤--------------', 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) => { // console.log('axios自定義介面卡-------------',config) var settle = require('axios/lib/core/settle'); var buildURL = require('axios/lib/helpers/buildURL'); //當baseURL為undefined時,不讓小程式端字首加上baseURL const baseURL= config.baseURL?config.baseURL:''; // console.log('config.baseURL--------------',config.baseURL), // console.log('buildURL(config.url, config.params, config.paramsSerializer)',buildURL(config.url, config.params, config.paramsSerializer)) uni.request({ method: config.method.toUpperCase(), url: 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("執行完成:", response) response = { data: response.data, status: response.statusCode, errMsg: response.errMsg, header: response.header, config: config }; settle(resolve, reject, response) } }) }) } export default service
注:當沒有配置axios的baseURL時,在小程式端會發生請求錯誤
出錯原因:
//沒有配置axios的baseURL時,小程式端會在每個請求前加上undifined
url: config.baseURL + buildURL(config.url, config.params, config.paramsSerializer),
解決方式:
const baseURL= config.baseURL?config.baseURL:''; ... url: baseURL + buildURL(config.url, config.params, config.paramsSerializer),
請求中使用axios例項
api/policy/policy.js
import service from '@/util/request' import { policy } from '@/api/url' export const addPolicy = data => { return service({ url: `${policy}/insure/insure/addInsure`, method: 'POST', data }) } //車型列表查詢 export const getCarList = data => { return service({ url: `${policy}/insure/insureAsset/searchInsureAssetListPage`, method: 'POST', data }) } //資產關聯屬性查詢 export const getAssetAndAttributeList = data =>{ return service({ url:`${policy}/insure/insureAsset/searchAssetAndAttributeListPage`, method: 'POST', data }) }
ps: api/url.js存放api的基路徑
//配置api的URL
const env = process.env.NODE_ENV
//https://website-pm-private.solarmanpv.com/oauth_dk
export const login = env === 'production'?'http://10.168.30.31:33005':'http://192.168.30.97:33005'
export const policy = env ==='production'?'http://192.168.30.97:50001':'http://192.168.30.97:50001'
export const message = env ==='prodction'?'':''