springboot解决跨域问题_SpringBoot服务器端解决跨域问题

SpringBoot解决跨域问题的两种方案:

1、通过给方法或者类加注解的形式,@CrossOrigin。

2、继承接口,重写addCorsMappings方法。

第一种方式:

@RestController
@CrossOrigin("http://localhost:8081")
public class BaseController {

 @GetMapping("/hello")
 public String testGet(){

  return "get";
 }

 @PutMapping("/doPut")
 public String testPut(){
  return "put";
 }
}

指定请求来源,可以写成“*”,表示接收所有来源的请求。

第二种方式:

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

 @Override
 public void addCorsMappings(CorsRegistry registry) {
  registry.addMapping("/**").allowedOrigins("http://localhost:8081")
    .allowedHeaders("*")
    .allowedMethods("*")
    .maxAge(30*1000);
 }
}

allowOrigins也可以写成allowedOrigins(" * "),表示接收所有来源的请求。

注意点:

1、路径来源的写法问题

如果后台指定路径来源为:http://localhost:8081

那么在浏览器里访问前端页面的时候,必须用 http://localhost:8081,不可以写成127.0.0.1或者本机ip地址。否则还是会报跨域错误。测试如下

后台设置:

@Override
 public void addCorsMappings(CorsRegistry registry) {
  registry.addMapping("/**").allowedOrigins("http://localhost:8081")
    .allowedHeaders("*")
    .allowedMethods("*")
    .maxAge(30*1000);
 }

前端请求:

<script>
    doGet = function () {
        $.get('http://localhost:8080/hello', function (msg) {
            $("#app").html(msg);
        });
    }
 
    doPut = function () {
        $.ajax({
            type:'put',
            url:'http://localhost:8080/doPut',
            success:function (msg) {
                $("#app").html(msg);
            }
        })
    }
</script>

启动服务,浏览器里访问:

http://localhost:8081/index.html

正常返回结果

浏览器里访问:

http://127.0.0.1:8081/index.html

报跨域错误如下:

ca286d247695aade9dc15725b4ee98fc.png

所以说,浏览器访问路径需要与后台allowOrigin里设置的参数一致。

那如果代码里的访问路径可以不一样吗,比如:

doGet = function () {
  $.get('http://127.0.0.1:8080/hello', function (msg) { //本机ip地址
   $("#app").html(msg);
  });
 }

 doPut = function () {
  $.ajax({
   type:'put',
   url:'http://192.168.1.26:8080/doPut',
   success:function (msg) {
    $("#app").html(msg);
   }
  })
 }

经过测试,是可以的,只要浏览器里访问页面的路径写法与后台保持一致就可以了。

2、携带Cookie

有时候,前端调用后端接口的时候,必须要携带cookie(比如后端用session认证),这个时候,就不能简单的使用allowOrigins("*")了,必须要指定具体的ip地址,否则也会报错。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值