后端接收不到前端传入的header参数信息
问题描述:
在局域网下,前端页面请求时在请求头里携带token信息,后台获取不到header里的token参数,但是使用postman却能够接受到参数。
String token = request.getHeader("accessToken");
if (!StringUtil.hasText(token)) {
token = request.getParameter("accessToken");
}
原因分析:
debug查看了下返回的request参数
host = 172.16.115.198:8080
connection = keep-alive
accept = */*
access-control-request-method = POST
access-control-request-headers = content-type,accessToken
origin = http://localhost:8080
user-agent = Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1
sec-fetch-mode = cors
referer = http://localhost:8080/
accept-encoding = gzip, deflate
accept-language = zh-CN,zh;q=0.9
用postman调接口的request参数
content-type = application/json;charset=utf-8
accessToken= 90E672B00F7005FF5468EFF8A5BDB4A1
user-agent = PostmanRuntime/7.26.8
accept = */*
postman-token = a0021135-db66-46c4-a1af-45f8542443b0
host = 127.0.0.1:8080
accept-encoding = gzip, deflate, br
connection = keep-alive
content-length = 392
cookie = JSESSIONID=2AA6371806B02CF13ADFE0A11E72A246; userKey=90E672B00F7005FF5468EFF8A5BDB4A1; sessionKey=90E672B00F7005FF5468EFF8A5BDB4A1****
发现cors跨域复杂请求会先发送一个方法为OPTIONS的预检请求,这个请求是用来验证本次请求是否安全的
第二个过滤器判断token时会把预请求当做真正的请求去判断,所以在第二个过滤器判断token之前先判断是不是预请求OPTIONS,不是则验证token,是则放行。
解决方案:
在判断token之前加判断语句
if (!request.getMethod().equals("OPTIONS")) {
String token = request.getHeader("accessToken");
if (!StringUtil.hasText(token)) {
token = request.getParameter("accessToken");
}
}