在vue传header数据的时候,会请求2次,一次是options
第二次才是get post请求
只需要把下面的代码给response设置内容
并且如果是options请求给他返回200 这样get post 再次访问的时候
后台获取 header就有数据了
/**
* 只登陆1次
*/
@Slf4j
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
/**
* 所有请求的过滤器
* @param request
* @param response
* @param filterChain
* @throws ServletException
* @throws IOException
*/
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
//origin:指定可以访问本项目的IP
String origin = request.getHeader("Origin");
response.setContentType("application/json;charset=UTF-8");
response.setHeader("Access-Control-Allow-Origin", origin);
response.setHeader("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "1800");
// 设置 受支持请求标头(自定义 可以访问的请求头 例如:Token)
response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization,token,Origin,Content-Type,Accept");
// 指示的请求的响应是否可以暴露于该页面。当true值返回时它可以被暴露
response.setHeader("Access-Control-Allow-Credentials", "true");
//如果是OPTIONS请求,让其响应一个 200状态码,说明可以正常访问
if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
return;
}
//获取token信息
String header=request.getHeader("Authorization");
log.info("header:{}",header);
//放行
filterChain.doFilter(request,response);
}
}
跨域也要配置好
package com.dmg.sp.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
//解决跨域
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
//设置允许跨域的域名
registry.addMapping("/**")
//设置允许跨域的域名
.allowedOriginPatterns("*")
//是否允许cookie
.allowCredentials(true)
//设置允许请求的方式
.allowedMethods(new String[]{"GET","POST","PUT","DELETE","OPTIONS"})
//设置允许的请求头
.allowedHeaders("*")
//跨域允许时间
.maxAge(3600);
}
}
vue的axios 拦截器的header传参