Spring RestTemplate调用API成功,但jQuery失败,因为同源策略 [英] Spring RestTemplate call to API worked but jQuery failed because same-origin policy

查看:0
本文介绍了Spring RestTemplate调用API成功,但jQuery失败,因为同源策略的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用Spring RestTemplate调用REST API时。

public class JiraBusImpl implements JiraBus {
  private RestTemplate restTemplate = new RestTemplate();

  HttpHeaders headers = BusUtils.createHttpHeaderWithDefaultBasicAuth();

  @Override
  public List<JIRAProject> getProjects() {
    HttpEntity<String> request = new HttpEntity<String>(headers);
    ResponseEntity<JIRAProject[]> response = restTemplate.exchange("http://jira_url:port/rest/api/2/project",
            HttpMethod.GET, request, JIRAProject[].class);
    JIRAProject[] projectsField = response.getBody();

    return Arrays.asList(projectsField);
  }
}

它正常工作,但当我使用jQuery调用时,它失败并抛出错误

XMLHttpRequest无法加载URL。对印前检查请求的响应未通过访问控制检查:请求的资源上不存在"Access-Control-Allow-Origin"标头。因此不允许访问源‘http://localhost:8080’。

以下是我的jQuery代码:

$.ajax({
  url: 'http://jira_url:port/rest/api/2/project',
  type: 'GET',
  dataType: 'json',
  beforeSend: function (xhr) {
    xhr.setRequestHeader ("Authorization", "Basic " + btoa('username' + ":" + 'password'));
  },
  success: function(data) {
    console.log(data);
  },
  error: function(jqXHR, textStatus, errorThrown) {
  }
});

RestTemplate如何做到这一点?

推荐答案

您可以使用@CrossOrigin()批注。

https://spring.io/guides/gs/rest-service-cors/

或仅添加筛选器以设置响应标头以允许跨源。

'Access-Control-Allow-Origin' error in Spring MVC + Zepto POST


在jQuery AJAX调用中,将其更改为dataType: "jsonp"以启用跨源。


对不起,我误会了。在Web浏览器上应用同源策略。 https://en.wikipedia.org/wiki/Same-origin_policy

您甚至可以将其关闭。Disable same origin policy in Chrome

这意味着首先,只要服务器端允许,任何客户端都可以访问REST服务。然而,出于安全考虑,网络浏览器会禁用它。因此,RestTemplate如何做到这一点并不是问题。这是因为Web浏览器将其禁用。

这篇关于Spring RestTemplate调用API成功,但jQuery失败,因为同源策略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆