本文导航 SpringBoot解决跨域问题的两种方案: 1、通过给方法或者类加注解的形式,@CrossOrigin。 2、继承接口,重写addCorsMappings方法。 第一种方式: @RestController@CrossOrigin("http://localhost:
          本文导航
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
报跨域错误如下:

所以说,浏览器访问路径需要与后台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地址,否则也会报错。
以上就是SpringBoot服务器端解决跨域问题的详细内容,更多关于SpringBoot 解决跨域的资料请关注易盾网络其它相关文章!
