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

When I use Spring RestTemplate to call a Rest API.

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

  HttpHeaders headers = BusUtils.createHttpHeaderWithDefaultBasicAuth();

  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:

  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) {
  error: function(jqXHR, textStatus, errorThrown) {

How can RestTemplate do that?

Answers 1

Related Articles