记录一次跨域产生的问题

背景: springboot +redis  

    webstorm + vue + axios

问题: options  请求中不带sessionid   发起post请求 会先发送options 请求 并返回302,get请求 sessionId每次不一样

跨域产生问题解决如下:

1.页面配置 axios.defaults.withCredentials = true    不写配置会产生sessionid 每次都不一样

sprngboot 配置: filter 中

    String curOrigin = request.getHeader("Origin");
            response.setHeader("Access-Control-Allow-Origin", curOrigin == null ? "true" : curOrigin);
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, PATCH, DELETE, PUT");
            response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");

配置这些之后,可以正常访问。 但是如果需要sessionID 所带的数据进行验证。或者出现302  那是因为发出了options请求  这个请求没有携带sessonId

可能还要

  String method = request.getMethod();
        if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
            chain.doFilter(req, resp);
            return ;
        }



import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class XXXMvcConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
         registry.addMapping("/**")
         .allowedOrigins("*")
         .allowCredentials(true)
         .allowedMethods("GET", "POST", "DELETE", "PUT","PATCH","OPTIONS")
         .maxAge(3600);
    }
}

这样就可以了。

这样之后的请求中就不会再有options  的请求。只有post请求。

猜你喜欢

转载自www.cnblogs.com/sunshine99/p/12944244.html
今日推荐