axios使用全局拦截器在请求头部添加token
用户登录成功后,后台会返回一个token,在之后发送的请求headers都要带上这个token,否则后台进行授权校验,如果token一致,则允许访问,否则请求不成功被拦截。
请求拦截器使用说明:https://github.com/axios/axios
axios Interceptors requests or responses before they are handled by then or catch(响应和请求)。
// Add a request interceptor
axios.interceptors.request.use(function (config) {
// Do something before request is sent
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});// Add a response interceptor
axios.interceptors.response.use(function (response) {
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
return response;
}, function (error) {
// Any status codes that falls outside the range of 2xx cause this function to trigger
// Do something with response error
return Promise.reject(error);
});
因此添加axios的全局拦截器即可,通过config.headers["Authorization"] = token;将token放到请求头发送给服务器,放入请求头中,使用keycloak获取token。
// interceptor axios http headers
axios.interceptors.request.use(
config => {// 发起请求前
config.headers["Authorization"] = `Bearer ${keycloak.token}`;
config.headers["Content-Type"] = "application/json";
return config;
},
error => {// 请求异常处理
Promise.reject(error);
}
);
If you need to remove an interceptor later you can.
const myInterceptor = axios.interceptors.request.use(function () {/*...*/}); axios.interceptors.request.eject(myInterceptor);
You can add interceptors to a custom instance of axios.
const instance = axios.create(); instance.interceptors.request.use(function () {/*...*/});