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地址。否则还是会报跨域错误。测试如下

扫描二维码关注公众号,回复: 12412412 查看本文章

后台设置:

 @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地址,否则也会报错。

最新2020整理收集的一些高频面试题(都整理成文档),有很多干货,包含mysql,netty,spring,线程,spring cloud、jvm、源码、算法等详细讲解,也有详细的学习规划图,面试题整理等,需要获取这些内容的朋友请加Q君样:11604713672

猜你喜欢

转载自blog.csdn.net/weixin_51495453/article/details/112503874