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就可以访问了 。。。

 

posted @ 2018-01-23 14:28  再也伤不起  阅读(31605)  评论(1编辑  收藏  举报