0

When I use Spring RestTemplate to call a 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);
  }
}

It worked normally, but when I use jQuery to call, it failed and throws an error

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.

Here is my jQuery code:

$.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) {
  }
});

How can RestTemplate do that?

dauruy
  • 329
  • 7
  • 13

1 Answers1

1

You can use @CrossOrigin() annotation.

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

Or just add a filter to set response header to allow cross origin.

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


In your jQuery ajax call, change it to dataType: "jsonp" to enable the cross origin.


Sorry for my misunderstanding. Same-origin policy is applied on web browser. https://en.wikipedia.org/wiki/Same-origin_policy

You can even turn it off. Disable same origin policy in Chrome

So that means at the first place, a rest service can be accessed by any clients if only the server side allows it. However, for safety issues, web browsers disable it. So it's not the problem how RestTemplate does it. It's because that web browser disable it.

Community
  • 1
  • 1
Duncan
  • 665
  • 1
  • 5
  • 15