springboot通过CORS(cross-origin resourse sharing 跨域资源共享)解决跨域问题

简单来说,源就是指协议,域名和端口号,所谓同源就是协议相同,域名相同,端口号相同,以下举个例子:
对于 http://www.aa.com/test/index.html 判断是否同源(协议为http协议,域名为www.aa.com,端口号为80(默认,可以省略))
1、http://www.aa.com/bb/index.html ——同源;
2、http://www.baidu.aa.com/bb/index.html ——非同源,域名不一致;
3、https://www.aa.com/bb/index.html ——非同源,协议不一致;
4、http://www.aa.com:8080/bb/index.html ——非同源,端口号不一致

同源策略

同源策略由Netscape提出的一个著名的安全策略,是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响。可以说Web是构建在同源策略基础之上的,浏览器只是针对同源策略的一种实现(引用自百度百科的定义)。传统的跨域方案时使用JSONP,但是JSONP只支持GET请求,不支持其他类型的请求,不过在spring框架中,也对于跨域资源共享也提供了解决方案。

实现

1、创建两个springboot项目,第一个名为study,端口为8080;第二个名为demo,端口为8081;
2、study项目在static目录下创建一个hello.html文件,内容如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test</title>
    <script type="text/javascript" src="js/jquery-3.6.0.min.js"></script>
</head>
<body>
  <div id="app"></div>
  <input type="button" onclick="btnClick()" value="get_button" />
  <input type="button" onclick="btnClick2()" value="post_button" />
</body>
<script>
  function btnClick() {
      $.get('http://localhost:8081/hello1', function (msg) {
      $('#app').html(msg);
    });
  }
  function btnClick2() {
    $.post('http://localhost:8081/hello2', function (msg) {
      $('#app').html(msg);
    });
  }
</script>
</html>

3、demo项目创建UserController.java类,内容如下:

package com.example.demo.controller;

import org.springframework.web.bind.annotation.*;

@RestController
public class UserController {

    @GetMapping("/hello1")
    public String hello() {
        return "get hello";
    }

    @PostMapping("/hello2")
    public String hello2() {
        return "post hello";
    }
}

4、启动两个项目,打开浏览器访问 http://localhost:8080/hello.html,页面如下
在这里插入图片描述
5、点击两个按钮,前端控制台报错:
在这里插入图片描述
6、在hello()和hello2()上面加上注解@CrossOrigin(“http://localhost:8080”),表示接受来自localhost:8080的请求,启动项目,再点击按钮,结果如下:

@GetMapping("/hello1")
    @CrossOrigin("http://localhost:8080")
    public String hello() {
        return "get hello";
    }

    @PostMapping("/hello2")
    @CrossOrigin("http://localhost:8080")
    public String hello2() {
        return "post hello";
    }

在这里插入图片描述
在这里插入图片描述
响应头中多了 Access-Control-Allow-Origin: http://localhost:8080,表示服务愿意接受来自 http://localhost:8080的请求,这样浏览器就不会去限制本次跨域请求了。
不过如果每一个方法上面都加上注解的话就比较麻烦,所以可以通过全局的配置解决这个问题,在demo项目的springmvc的配置类中配置一下即可,配置文件如下

package com.example.demo.config;

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

@Configuration
@Component
public class WebMvcConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")  // 所有方法都会处理跨域请求
                .allowedOrigins("http://localhost:8080")    // 允许请求的域名
                .allowedHeaders("*")    // 允许的请求头
                .allowedMethods("GET","POST");  // 允许的请求方式
        WebMvcConfigurer.super.addCorsMappings(registry);
    }
}

重启项目,点击两个按钮,结果如下:
在这里插入图片描述
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值