我想将自定义标头从Spring Rest Controller发送到AngularJS中的UI客户端。我已经在StackOverFlow中查看了答案,但是没有一种解决方案对我有用。
这是我的Spring CORS属性设置;
cors:
allowed-origins: "*"
allowed-methods: GET, PUT, POST, DELETE, OPTIONS
allowed-headers: "*"
exposed-headers: Header-Error
allow-credentials: true
max-age: 1800
Spring Controller,我将Header-Error发送回我的自定义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);
}
在AngularJS端,我发送的请求如下:
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));
});
当我收到响应时,在响应中看不到我的自定义标头:
{
"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": ""
}
但是在浏览器中,我看到我的客户标头Header-Error是响应的一部分,
非常感谢。
答案 0 :(得分:0)
我设法解决了这个问题。在从How to read response headers in angularjs? 阅读解决方案之后,我更改了$ http.get
的签名后,问题出在angularjs上。来自
$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));
});
到
$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));
});
请注意,headers变量代表一个函数而不是JS对象,因此您需要传递标题名称以检索该值。所以在我的情况下,我通过了“ Header-Error”。
谢谢。