I create a RESTful API
with Spring boot
and host it in Pivotal web services
.
Let's say the url is https://abc.cfapps.io/students and the json result will be
[
{"id":1,"name":"Michael","score":8.5},
{"id":2,"name":"Naomi","score":5.6}
]
Then I write an Angular client to send a request to that url:
angular.module("app", []).controller("listController", function($scope, $http)
{
var url = 'https://abc.cfapps.io/students';
var httpRequest = new XMLHttpRequest();
httpRequest.open('GET', url, true);
httpRequest.setRequestHeader('Access-Control-Allow-Origin', '*');
httpRequest.setRequestHeader('Content-Type', 'application/json');
httpRequest.onerror = function (XMLHttpRequest, textStatus, errorThrown) {
console.log('failed');
console.log(JSON.stringify(XMLHttpRequest));
};
httpRequest.onload = function () {
console.log('SUCCESS!');
}
httpRequest.send();
});
My client run in localhost:52442
and in my Spring boot service
I also allow CORS
, too.
@RestController
@CrossOrigin(origins = "http://localhost:52442")
@RequestMapping(value="/students")
public class StudentService
{
@RequestMapping(value="/",method = RequestMethod.GET)
public ArrayList<Student> getListStudents()
{
// return list
}
// other methods
}
But I keep getting this error:
XMLHttpRequest cannot load https://abc.cfapps.io/students.
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:52442' is therefore not allowed access. The response had HTTP status code 403.