I want to send custom header to from Spring Rest Controller to UI client in AngularJS. I have gone over answers here in StackOverFlow, however none of the solutions have worked for me.
here are my Spring CORS properties settings;
cors:
allowed-origins: "*"
allowed-methods: GET, PUT, POST, DELETE, OPTIONS
allowed-headers: "*"
exposed-headers: Header-Error
allow-credentials: true
max-age: 1800
Spring Controller, I am sending back the Header-Error as my custom Header:
public ResponseEntity<Void> startOauthToken(@PathVariable("seller") String seller){
// do something....
MultiValueMap<String, String> headers = new HttpHeaders();
headers.add("Header-Error","Account already is register with the system!!");
return new ResponseEntity<Void>( headers, HttpStatus.BAD_REQUEST);
}
On the AngularJS side, I am sending the request as follows:
var url = APP_CONFIG.apiRootUrl + 'api/v1/startOauthToken/'+value;
$http.get(url).success(function (response){
console.log("Vaue of the response is " + JSON.stringify(response));
})
.error(function(response){
console.log("Value of error " + JSON.stringify(response));
});
when I receive response, I do not see the my custom header in the response:
{
"data": "",
"status": 400,
"config": {
"method": "GET",
"transformRequest": [null],
"transformResponse": [null],
"url": "http://localhost:8082/api/v1/startOauthToken/somevalue",
"headers": {
"Accept": "application/json, text/plain, */*",
"Authorization": "Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ0ZXN0QHRlc3QiLCJhdXRoIjoiUk9MRV9URU5BTlRfQURNSU4iLCJleHAiOjE1MzIwODU3MjV9.YdKPP63ZqQVGD9EZOtBu0aniP2R4uNllAEe-O8BiOjTKqgIiAQGCW9PcLSb1jp6Epvz3bzRcnPvKn0d2Gg4PHw"
}
},
"statusText": ""
}
However in the Browser I can see that my customer header Header-Error is received as part of the response,
many thanks.
I have managed to resolved the issue. The issue was on the angularjs side after, after reading solution from How to read response headers in angularjs? , I changed the signature of the $http.get
from
$http.get(url).success(function (response){
console.log("Vaue of the response is " + JSON.stringify(response));
})
.error(function(response){
console.log("Value of error " + JSON.stringify(response));
});
to
$http.get(url).success(function (data , status, headers, config){
console.log("Info data " + JSON.stringify(data));
console.log("Info status " + JSON.stringify(status));
console.log("Info headers " + headers('Header-Error'));
console.log("Info config " + JSON.stringify(config));
})
.error(function(data , status, headers, config){
console.log("Info data " + JSON.stringify(data));
console.log("Info status " + JSON.stringify(status));
console.log("Info headers " + headers('Header-Error'));
console.log("Info config " + JSON.stringify(config));
});
Please note the headers variable represents a function rather then JS object, so you need to pass the header name to retrieve the value. so In my case I passed the 'Header-Error'.
thanks.