fetch 添加拦截器拦截器
使用过axios的便会知道axios 有axios.interceptors.request.use请求拦截器与service.interceptors.response.use响应拦截器,可以请求前和,then,catch前统一处理响应信息或者response
expand_fetch.js
const req_interceptors = [] //请求拦截方法存放
const res_interceptors = [] //响应拦截方法存放
function expand_fetch( url, option = { } ){
if( !option.method ){
option.method = 'GET'
}
//多个请求拦截器依次更改option
req_interceptors.forEach( fn => option = fn(option) )
return new Promise((resolve,reject)=>{
//使用原生fetch
fetch(url,option).then(( res )=>{‘
//多个响应拦截器依次更改res
res_interceptors.forEach( fn => res = fn(res) )
resolve(res)
})
.catch((error)=>{
reject(error)
})
})
}
//挂载添加和删除拦截器的方法
expand_fetch.interceptors = {
request:{ use : (fn)=>{
req_interceptors.push(fn)
return fn
},
eject:(data)=>{
if(req_interceptors.indexOf(data) !== -1){
req_interceptors.splice(req_interceptors.indexOf(data),1)
}
}
},
response:{ use : (fn)=>{
res_interceptors.push(fn)
return fn
}},
eject:(data)=>{
if(res_interceptors.indexOf(data) !== -1){
res_interceptors.splice(res_interceptors.indexOf(data),1)
}
}
}
export default expand_fetch
使用
import Fetch from './expand_fetch.js'
//为post数据转为 json 发送
const c_req = Fetch.interceptors.request.use((option)=>{
if(option.method === "POST"){
option.body = JSON.stringify(option.body)
}
return option
})
//直接获取到返回内容的数据
const c_res = Fetch.interceptors.response.use((res)=>{
if(res.code === 200 && res.data ){
return res.data
}
return res
})
//清除拦截器
Fetch.interceptors.request.eject(c_req)
Fetch.interceptors.response.eject(c_res)