zoukankan      html  css  js  c++  java
  • 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就可以访问了 。。。

  • 相关阅读:
    Jmeter 跨脚本入参
    Jmeter 查看结果树显示unicode转中文
    jmeter+ant 接口自动化测试框架
    jmeter jmeter.results.shanhe.me.xsl 模板内容
    Jmeter + ant 接口自动化测试(进阶)
    Linux od命令
    Hadoop初识
    tbn tbc tbr
    ffmpeg之avcodec_open2
    ffmpeg之AVStream
  • 原文地址:https://www.cnblogs.com/xuyou551/p/8335623.html
Copyright © 2011-2022 走看看