Spring 对 API 的 RestTemplate 调用有效但 jQuery 失败,因为同源策略

Spring RestTemplate call to API worked but jQuery failed because same-origin policy

当我使用 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 cannot load url. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

这是我的 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 服务。但是,出于安全问题,Web 浏览器将其禁用。所以这不是 RestTemplate 怎么做的问题。这是因为网络浏览器禁用了它。