比较两种请求方式
- 1.使用原生提供的fetch
- 2.使用第三方封装库:axios
- Vue中可以统一对axios进行挂载
Vue.prototype.$http = axios
- 3.比较fetch和axios
- axios 对已获得的数据进行了一层封装 XSRF
- fetch并没有进行封装,拿到就是格式化后的数据
- fetch进行了多一层的格式化
- res.json()
- res.blob() 格式化二进制
- res.text()
- 3.更多详情请参考:axios和fetch请求详解
axios封装
function request ({
url,
method = 'get' || 'GET',
headers,
params,
data,
baseURL,
auth,
withCredentials = false
}) {
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
axios.defaults.baseURL = baseURL
return new Promise(function ( resolve,reject ) {
console.log('method',method)
switch ( method.toUpperCase() ) {
case 'get' || 'GET':
axios({
url,
params,
}).then( res => resolve( res ))
.catch( err => reject( err ))
break;
case 'POST':
console.log('post - p')
const p = new URLSearchParams()
if ( data ) {
for( let key in data ) {
p.append( key, data[ key ] )
}
}
axios({
url,
data: p,
method,
auth,
withCredentials
}).then( res => resolve( res ))
.catch( err => reject( err ))
break;
case 'PUT':
axios({
url,
params,
method
}).then( res => resolve( res ))
.catch( err => reject( err ))
break;
case 'DELETE':
axios({
url,
params,
method
}).then( res => resolve( res ))
.catch( err => reject( err ))
break;
default:
break;
}
})
}
fetch请求封装
function obj2String(obj, arr = [], idx = 0) {
for (let item in obj) {
arr[idx++] = [item, obj[item]]
}
return new URLSearchParams(arr).toString()
}
function commonFetcdh(url, options, method = 'GET') {
const searchStr = obj2String(options)
let initObj = {}
if (method === 'GET') {
url += '?' + searchStr
initObj = {
method: method,
credentials: 'include'
}
} else {
initObj = {
method: method,
credentials: 'include',
headers: new Headers({
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded'
}),
body: searchStr
}
}
fetch(url, initObj).then((res) => {
return res.json()
}).then((res) => {
return res
})
}
function GET(url, options) {
return commonFetcdh(url, options, 'GET')
}
function POST(url, options) {
return commonFetcdh(url, options, 'POST')
}
GET('https://www.baidu.com/search/error.html', {a:1,b:2})
POST('https://www.baidu.com/search/error.html', {a:1,b:2})