码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-01-23 15:52:29      阅读:1456      评论:0      收藏:0      [点我收藏+]

标签:.com   map   stc   function   添加   http   head   port   访问   

 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注解解决细粒度的配置跨域

标签:.com   map   stc   function   添加   http   head   port   访问   

原文地址:https://www.cnblogs.com/xuyou551/p/8335623.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!