目录
-
- axios的二次封装与拦截器
-
- network/request.js 请求拦截等
- 具体使用
axios的二次封装与拦截器
- 官网:
https://www.npmjs.com/package/axios#interceptors
- 就是在请求发出去之前的操作!
- 比如:请求的时候需要携带token值,需要一个loading等效果!
network/request.js 请求拦截等
import axios from "axios";
import store from "../store/index"
import {message
} from "antd"
const request = axios.create({baseURL: 'http://120.76.247.5:2001/api',withCredentials: true,
})
request.interceptors.request.use(function (config) {const state = store.getState()config。baseUrl = 'XXX 就是你请求的base基础路径,这样的话,就不用服务器代理了';config.headers.authorization = state.user.Authorizationmessage.loading({content: '努力加载中....',duration: .5});return config;
}, function (error) {return Promise.reject(error);
});
request.interceptors.response.use(function (response) {return response
}, function (error) {return Promise.reject(error)
})
export async function get(url, data, config = {}) { const {data: result} = await request({...config,method: "get",url,params: data})return result
}
export async function post(url, data, config = {}) {const {data: result} = await request({...config,url,method: 'post', data})return result
}
export async function put(url, data, config = {}) {const {data: result} = await request.put(url, data, config);return result;
}
export async function remove(url, data, config = {}) {const {data: result} = await request.delete(url, {...config,params: data});return result;
}export default {get,post,put,remove
}
具体使用
<Suspense fallback={<div>loading...</div>} ><Switch><Route path="/login" component={Login}></Route><Route path="/reg" component={Reg}></Route><Route path="/home" component={Home}></Route><Route path="/about" component={About}></Route><Route path="/cart" component={Cart}></Route><Route path="/iq/:id" component={IQ} /><Route path="/mine" component={Mine}></Route><Redirect path="/" to="/home" exact ></Redirect></Switch></Suspense>