SpringBoot2.x跨域问题

本文介绍了跨域的概念,指出当协议、域名或端口号不同时即为跨域,并通过实例解释了同源和跨域的区别。同源策略限制了DOM操作和XHR请求只能在同源之间进行。针对这一策略,文章提供了两种SpringBoot的跨域解决方案:使用@CrossOrigin注解和配置WebMvcConfigurer以允许跨域请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.什么是跨域

1.1 跨域

协议、域名、端口号,至少一个不相同,就是跨域访问

1.2 同源

协议、域名、端口号,全部一样,就是同源

1.3 举例

对比跨域比较:
https://www.baidu.com/index.html

https://www.baidu.com/more/index.html 不跨域 三要素相同
https://map.baidu.com/ 跨域 域名不同
http://www.baidu.com/index.html 跨域 协议不同
https://www.baidu.com:8081/index.html 跨域 端口号不同

2. 同源策略

2.1 DOM同源策略

禁止对不同源页面DOM 进行操作。这里主要场景是iframe跨域的情况,不同域名的iframe是限制互相访问的。

2.2 XMLHttpRequest同源策略

禁止使用XHR对象向不同源的服务器地址发起HTTP请求。

3. Spring Boot跨域解决

3.1 方式1:在请求上添加 @CrossOrigin 注解

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
public class HelloController {
 
 @CrossOrigin
 @RequestMapping("/hello")
 public String HelloSpring (){
  return "hello cors";
 }
}

3.2 方式2:WebMvcConfigurer配置类

import org.springframework.context.annotation.Bean;
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 MyConfiguration {
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/*")
                        .allowedOriginPatterns("*")
                        .allowCredentials(true)
                        .allowedMethods("GET", "POST", "DELETE", "PUT","PATCH")
                        .maxAge(3600);
            }
        };
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

神奇洋葱头

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值