一、fetch
原生js新增 用于请求数据
fetch(url,{
headers:{
"token":localStorage.getItem('token'),
"content-type":"apllication-xxx-urlencoded"
},
method:"GET/POST",
data:{
}
}).then(function(res){
//设置返回格式 text() arrayBuffer() blob() formData()
return res.json()
}).then(res=>{
//res 才是请求的结果 格式化之后(什么格式取决于 第一个 then 返回的处理方法)
})
二、axios
get请求方式
//地址栏传数据
axios.get('url?userName=xxx').then(res=>{}).catch(err=>{})
axios.get(url,{
params:{
userName:"xxx"
},
headers:{
}
}).then(res=>{}).catch(err=>{})
post请求
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (res) {
console.log(res);
})
.catch(function (error) {
console.log(error);
});
完整请求
axios({
method: 'post',
url: '/user/12345',
headers:{
},
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
}).then().catch()
创实例
可以对所有的请求,做一些初始化配置,配置是作用域所有的用实例的请求
const instance = axios.create({
baseURL: 'https://some-domain.com/api/',
headers: {'X-Custom-Header': 'foobar'}
});
//instance.get("/gateway", { params:{ }}).then(res=>{})
//instance.post("/gateway", {data:{ }}).then(res=>{})
axios拦截器
拦截请求响应
// 添加 请求 拦截器
axios.interceptors.request.use(function (config) {
// 可以在请求发送之前做一些事情 config 请求信息 config.headers
return config;
}, function (error) {
// 出错了 走这里
return Promise.reject(error);
});
// 添加相应拦截
axios.interceptors.response.use(function (response) {
// 在2xx范围内的任何状态代码都会触发此函数(请求成功触发)
// 在相应数据 发送到 ajax之前,可以在这里拦截
return response;
}, function (error) {
// 任何超出2xx范围的状态码都会触发此函数(请求失败触发)
// 响应失败执行
return Promise.reject(error);
});