springboot的@CrossOrigin注解解决细粒度的配置跨域

Posted 再也伤不起

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot的@CrossOrigin注解解决细粒度的配置跨域相关的知识,希望对你有一定的参考价值。

 1 import java.util.HashMap;
 2 
 3 import org.springframework.web.bind.annotation.CrossOrigin;
 4 import org.springframework.web.bind.annotation.RequestMapping;
 5 import org.springframework.web.bind.annotation.RequestMethod;
 6 import org.springframework.web.bind.annotation.RequestParam;
 7 import org.springframework.web.bind.annotation.RestController;
 8 
 9 /**
10  * @author wujing
11  */
12 @RestController
13 @RequestMapping(value = "/api", method = RequestMethod.POST)
14 public class ApiController {
15         
16     @CrossOrigin(origins = "http://172.16.71.27:8080")
17     @RequestMapping(value = "/get")
18     public HashMap<String, Object> get(@RequestParam String name) {
19         HashMap<String, Object> map = new HashMap<String, Object>();
20         map.put("title", "hello world");
21         map.put("name", name);
22         return map;
23     }
24 }
 1     <script>
 2         $(function() {
 3             $(\'#title\').click(function() {
 4 //                 alert(\'点击了\');
 5                 $.ajax({
 6                     url : "http://localhost:8081/api/get",
 7                     type : "POST",
 8                     data : {
 9                         name : "测试"
10                     },
11                     success : function(data, status, xhr) {
12                         console.log(data);
13                         alert(data.name);
14                     }
15                 });
16             });
17         })
18     </script>

特别注意:

 1:一定要在某类 或者某方法上 添加类似 method = RequestMethod.POST 的属性 

eg: @RequestMapping(value = "/api", method = RequestMethod.POST)
2:在某个方法上添加
@CrossOrigin 注解时 origins 属性一定要写ip号 如果输入localhost有时会出现403错误
eg:@CrossOrigin(origins = "http://172.16.71.27:8080")

 

 POST http://localhost:8081/api/get 403 ()
 Failed to load http://localhost:8081/api/get: No \'Access-Control-Allow-Origin\' header is present on the requested resource. Origin \'http://172.16.71.27:8080\' is therefore not allowed access. The response had HTTP status code 403.

把localhost换成ip 172.16.71.27就可以访问了 。。。

 

以上是关于springboot的@CrossOrigin注解解决细粒度的配置跨域的主要内容,如果未能解决你的问题,请参考以下文章

SpringBoot跨域(CORS)支持:注解@CrossOrigin

@CrossOrigin springboot里面使用跨域

SpringBoot CORS 跨域 @CrossOrigin

springboot项目跨域问题解决

Web跨域请求及SpringBoot项目解决方案

@CrossOrigin 注解 http.csrf().disable() 有啥区别?