跨域解决方案—SpringBoot CORS

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/shenzhen_zsw/article/details/89645241

跨域解决方案—SpringBoot CORS

浏览器同源策略

CORS定义

CORS头部定义

不支持跨域报错

支持CORS步骤

全局支持

package com.mooc.house.api.inteceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class WebMvcConf extends WebMvcConfigurerAdapter {

  @Autowired
  private AuthInterceptor authInterceptor;
  
  @Autowired
  private AuthActionInterceptor authActionInterceptor;
  
  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(authInterceptor).excludePathPatterns("/static").addPathPatterns("/**");
    registry
        .addInterceptor(authActionInterceptor)
         .addPathPatterns("/house/toAdd")
        .addPathPatterns("/accounts/profile").addPathPatterns("/accounts/profileSubmit")
        .addPathPatterns("/house/bookmarked").addPathPatterns("/house/del")
        .addPathPatterns("/house/ownlist").addPathPatterns("/house/add")
        .addPathPatterns("/house/toAdd").addPathPatterns("/agency/agentMsg")
        .addPathPatterns("/comment/leaveComment").addPathPatterns("/comment/leaveBlogComment");
    
    super.addInterceptors(registry);
  }


  /**
   * 处理跨浏览器请求
   * @param registry
   */
  @Override
  public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**")  // 拦截所有的url
        .allowedOrigins("*")    // 放行哪些原始域,比如"http://domain1.com,https://domain2.com"
        .allowCredentials(true) // 是否发送Cookie信息
        .allowedMethods("GET", "POST", "PUT", "DELETE") // 放行哪些原始域(请求方式)
        .allowedHeaders("*");   // 放行哪些原始域(头部信息)
    super.addCorsMappings(registry);
  }
  

}

说明:

    1)覆盖WebMvcConfigurerAdapter 中的addCorsMappings方法;

     2)通过上面方式就可以解决跨域的问题;


 

CORS两种请求


 

非简单的请求例子

基于上面发送请求,通过浏览器开发工具查看,可以发现请求了2次

说明:

     1)第1个请求中,请求头中多了一个Access-Control-Request-headers;

     2)第2个请求时正常的CORS请求,里面添加了Origin,还发送了Cookie1

猜你喜欢

转载自blog.csdn.net/shenzhen_zsw/article/details/89645241
今日推荐