原因分析
由于是前后端分离项目,请求涉及跨域
在前后端分离跨域的情况下,默认reponse header只能取到以下
- Content-Language
- Content-Type
- Expires
- Last-Modified
- Pragma
5个默认值,要想取得其他的字段需要在服务器端设置Access-Control-Expose-Headers 配置前端想要获取的header
代码示例
错误示例
后端
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
httpServletResponse.addHeader("ttt", "Try it out");
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
前端
Axios.interceptors.response.use(res => {
console.log(res)
return res.data;
}, error => {
Message({
message: error.response.data.message,
type: 'error'
})
return Promise.reject(error.response);
})
浏览器打印结果
正确示例
后端
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
httpServletResponse.addHeader("ttt", "Try it out");
httpServletResponse.setHeader("Access-Control-Expose-Headers", "ttt");
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
浏览器打印结果