公司項(xiàng)目要求用H5寫 作為一個(gè)iOS菜鳥搞起來(lái)啊,首先是搭建項(xiàng)目框架,項(xiàng)目框架直接用vue-cli搭建好,接下來(lái)是網(wǎng)絡(luò)請(qǐng)求的封裝,之前寫過(guò)一個(gè)小項(xiàng)目網(wǎng)絡(luò)請(qǐng)求用的vue-resource 后來(lái)看到尤雨溪大神推薦用Axios 再網(wǎng)上看了很多網(wǎng)絡(luò)請(qǐng)求的封裝,都不是很滿意,最后總結(jié)了一下封裝了一個(gè)網(wǎng)絡(luò)請(qǐng)求
首先創(chuàng)建一個(gè)網(wǎng)絡(luò)請(qǐng)求的Js文件
// 引入axios
import axios from 'axios'
// 這里是我在token過(guò)期的情況 調(diào)用原生的登錄方法
var jsbridge = require('../../static/js/jsbridge.js')
var Rxports = {
ajax: function (opt) {
var opts = opt || {}
if (!opts.url) {
return false
}
var token = sessionStorage.getItem('token')
axios({
// 請(qǐng)求方式
method: opts.type || 'post',
// 請(qǐng)求url
url: opts.url,
// 請(qǐng)求參數(shù)
params: opts.data || {},
// 請(qǐng)求頭
headers: opts.headers || {
'Content-Type': 'application/json',
'X-Requested-With': 'XMLHttpRequest',
'source': 'ios',
'token': token
},
// 請(qǐng)求超時(shí)時(shí)間
timeout: opts.time || 10 * 1000,
responseType: opts.dataType || 'json'
}).then(function (res) {
// 下面的是根據(jù)業(yè)務(wù)需求做的處理
if (res.data.code === 'ACK') {
if (opts.success) {
opts.success(res.data.data, res)
} else {
opts.error('網(wǎng)絡(luò)請(qǐng)求錯(cuò)誤,請(qǐng)稍后再試', res)
}
} else if (res.data.code === 'BUSINESS_ERROR') {
if (opts.error) {
opts.error(res.data.message, res)
} else {
opts.error('網(wǎng)絡(luò)請(qǐng)求錯(cuò)誤,請(qǐng)稍后再試', res)
}
} else if (res.data.code === 'NACK') {
if (opts.error) {
opts.error(res.data.message, res)
} else {
opts.error('網(wǎng)絡(luò)請(qǐng)求錯(cuò)誤,請(qǐng)稍后再試', res)
}
}
}).catch(function (error) {
// token過(guò)期的情況調(diào)用原生方法
if (error.response.data.code === 'UNAUTHORIZED') {
jsbridge.setupWebViewJavascriptBridge(function (bridge) {
bridge.callHandler('goLogin', function (response) {
})
})
sessionStorage.removeItem('token')
} else {
if (opts.error) {
opts.error(error, error)
} else {
opts.error('網(wǎng)絡(luò)請(qǐng)求錯(cuò)誤,請(qǐng)稍后再試', error)
}
}
})
}
}
export default Rxports
最后使用方法
import api from '../fetch/api'
api.ajax({
'type': 'post',
'url': '', // 請(qǐng)求url
'params': {
// 請(qǐng)求參數(shù)
},
'success': function (data) {
// 請(qǐng)求成功處理
},
'error': function (error) {
// 錯(cuò)誤原因提示
Toast(error)
}
})
這么看起來(lái),也是挺簡(jiǎn)單的