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就可以訪問了 。。。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM