使用ajax跨域请求时,后台无法获取到token
背景:
项目前后端分离,前台页面使用ajax请求后端的api。
前端写法:
var token=”Bearer eyJhbGciOiJIUzUxMiJ9.eyJleHAiOjE1MTAyNDEwMDAsInVzZXJJZCI6IsK_XHUwMDEywpbCi8KBwqhSwpjDp8KgU8KaXcKlwrDDryJ9.LuUr3I_eOOugcffmEhedc9wdWrOg5roY7WxREg1ddPpijDYLBlo5UWFYTgjnY2TWrYcN0MFkBODNYReOObYhiQ”;
$.ajax({
url: ‘http://IP或域名:8080/api/hello’,
beforeSend: function(request) {
request.setRequestHeader(“authorization”, token);
},
dataType: ‘JSON’,
async: false,//请求是否异步,默认为异步
type: ‘POST’,
success: function (data) {
},
error: function () {
}
});
后端控制器:
@CrossOrigin(origins = “*”, maxAge = 3600)
@RequestMapping(value = “/api/hello” )
public String hello(@RequestHeader(value = JwtUtil.USER_ID,defaultValue = “world”) String userID) {
return “hello ” + userID;
}
过滤器:继承了org.springframework.web.filter.OncePerRequestFilter
@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
//下面一行代码,在跨域情况下token始终是null,不跨域的时候正常。
String token = request.getHeader(HEADER_STRING);
//省略无关代码…….
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
原因:
经多次测试发现 ,在跨域的情况下,发现每次客户端请求接口的时候,都会有一个 OPTIONS 请求。
解决:
在doFilterInternal方法中加入以下代码。如果是OPTIONS请求直接放过即可。
if ( httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name()) ) {
filterChain.doFilter(httpServletRequest,httpServletResponse);
return;
}
修改一下控制器注解 @RequestMapping(value = “/api/hello” ) 改成:
@RequestMapping(value = “/api/hello”,method = {RequestMethod.POST,RequestMethod.OPTIONS} )