0

我想将自定义标头从 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 作为响应的一部分被接收,

在此处输入图像描述

非常感谢。

4

1 回答 1

0

我已经设法解决了这个问题。在阅读了如何在 angularjs 中读取响应标头的 解决方案之后,问题出现在 angularjs 方面。,我更改了 $http.get 的签名

$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 对象,因此您需要传递标头名称来检索值。所以在我的情况下,我通过了“标题错误”。

谢谢。

于 2018-07-21T18:42:32.190 回答