【问题标题】:No 'Access-Control-Allow-Origin' header - Springboot没有“Access-Control-Allow-Origin”标头 - Spring Boot
【发布时间】:2018-06-21 08:19:15
【问题描述】:

当我尝试访问我的 springboot restservice 时出现以下错误:

“加载http://localhost:8080/Lerneinheit 失败:对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,源“http://localhost:8081”不存在允许访问。响应的 HTTP 状态代码为 403。"

我在 Google 上搜索了很多并将其添加到我的 RestController 类中:“@CrossOrigin(origins = "http://localhost:8081")"

@CrossOrigin(origins = "http://localhost:8081")
@RestController
@RequestMapping("/Lerneinheit")
public class LerneinheitController {

    @Autowired
    LerneinheitRepository lerneinheitRepository;


    @RequestMapping(method=RequestMethod.GET)
    public List<Lerneinheit> getAllLerneinheiten(){
        List<Lerneinheit> lerneinheiten = new ArrayList<Lerneinheit>();
        for(Lerneinheit l : lerneinheitRepository.findAll())
            lerneinheiten.add(l);

        return lerneinheiten;
    }

这是我访问数据的 jQuery 代码:

var data = {}
    data["query"] = $("#query").val();

    $.ajax({
        type : "POST",
        contentType : "application/json",
        url : "http://localhost:8080/Lerneinheit",
        data : JSON.stringify(data),
        dataType : 'json',
        timeout : 100000,
        success : function(data) {
            console.log("SUCCESS: ", data);

        },
        error : function(e) {
            console.log("ERROR: ", e);

        },
        done : function(e) {
            console.log("DONE");
        }
    });

服务器在端口 8080 上运行,我的客户端页面在端口 8081 上运行 "gulp-live-server": "0.0.31"。

我尝试了很多,如果有人可以帮助我,那就太棒了。

干杯, JohnRamb0r

【问题讨论】:

  • 响应的 HTTP 状态码为 403——这就是你需要解决的问题。见en.wikipedia.org/wiki/HTTP_403。该 403 响应意味着您的服务器代码的其他部分禁止访问 /Lerneinheit 路径。并且将@CrossOrigin 添加到该Java 类将无法解决该问题。您需要在应用程序代码的那部分之前在服务器端的其他一些代码中修复它。您在该浏览器消息中看到提到 Access-Control-Allow-Origin 的唯一原因是因为您的服务器 - 像大多数服务器一样 - 没有将应用程序集标头添加到 4xx 响应。

标签: jquery spring-boot gulp cross-domain same-origin-policy


【解决方案1】:

有多种方法可以解决这个跨域请求问题: link

其中一种方法是在您的情况下使用 JSONP,如下所示:

$.ajax({
    url: http://localhost:8081/Lerneinheit,
    dataType: "jsonp",
    jsonp: "callback",
    success: function( response ) {
        /* fetch the response and do the processing */

        };
    }
});

删除 - @CrossOrigin(origins = "http://localhost:8081")

【讨论】:

  • 感谢您的回答。我将代码更改为此,现在我收到此错误:“script.js:1 GET localhost:8080/…{}&_=1515756837596 net::ERR_ABORTED”
  • JSONP 适用于 GET 方法。我没有注意到上面是post,我的错。尝试添加“Allow-control-Allow-origin”chrome插件,假设您使用chrome作为客户端发送请求并添加回@CrossOrigin(origins =“localhost :8081") 另外,这是您尝试实现的类似示例的link
猜你喜欢
  • 2016-01-21
  • 1970-01-01
  • 2018-09-25
  • 2017-09-19
  • 2015-04-02
  • 2020-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多