一、下载
npm install whatwg-fetch --save
二、在src目录下创建文件service封装下fetch
src/service/fetch.js
import 'whatwg-fetch'
export default{
post(url,data){
return fetch(url,
{
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json',
'accesstoken':sessionStorage.getItem('token')
}
}
)
},
get(url,params){
//get带参数请求,需要将数据拼接在url中
if(params){
let paramsArray=[]
// console.log(Object.keys(params)) //输出Array 数组
Object.keys(params).forEach(key=>{ //枚举属性,返回值去循环
// console.log(key)//输出 tab
paramsArray.push(key+'='+params[key])
})
if(url.search(/\?/)===-1){
url+='?'+paramsArray.join('&')
}else{
url+='&'+paramsArray.join('&')
}
}
return fetch(url)
}
}
三、提供公共木块数据,跟请求封装
src/service/api.js
import req from './fetch'
let Url = "URL"
const get=(params)=>{
return req.get(Url,{params}).then(res=>res.json())
}
export get
const post=(params)=>{
return req.post(Url,params).then(res=>res.json())
}
export post
四、组件中使用
impor {get, post} form 'src/service/api'
get(params).then(res=>{
});
post(params).then(res => {
});