跨域解决方案—SpringBoot CORS

目录

跨域解决方案—SpringBoot CORS

浏览器同源策略

CORS定义

CORS头部定义

不支持跨域报错

支持CORS步骤

全局支持

CORS两种请求

非简单的请求例子


 

 

跨域解决方案—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

 


 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值