spring - 访问控件为自定义响应头AngularJS公开标头配置

  显示原文与译文双语对照的内容
0 0

i reading reading,但我在我的CORS头上添加了一个,我在一个资源上实现自定义响应头,但我没有正确配置配置。

以下是我在资源的获取请求上收到的标头: 我收到一个"史蒂夫"的'响应标头',它应该被'access-control-expose-headers"所允许'


Access-Control-Allow-Headers:x-requested-with, Request-Header, Response-Header
Access-Control-Allow-Methods:POST, GET, OPTIONS, DELETE
Access-Control-Allow-Origin:*
Access-Control-Expose-Headers:Response-Header
Response-Header:Steve

但是 Angular 仍然不能访问这个定制的标题。 返回自定义请求标头,但不返回自定义响应标头:


{
"data": {
"id": 2,
"content":"Hello, frank!"
 },
"status": 200,
"config": {
"method":"GET",
"transformRequest": [
 null
 ],
"transformResponse": [
 null
 ],
"url":"http://localhost:8080/greeting",
"headers": {
"Accept":"application/json, text/plain, */*",
"Request-Header":"frank"
 }
 },
"statusText":"OK"
}

Angular 1.3 $httpProvider.interceptor:


'use strict';
angular
. module('headerDemoUiApp')
. factory('AuthInterceptor', function AuthInterceptor(nameService) {

 return {
 request: handleRequest,
 response: handleResponse
 };

 function handleRequest(config) {
 if (angular.isDefined(config.headers)) {
 config.headers['Request-Header'] ="frank";
 }
 return config;
 }

 function handleResponse(response) {
 console.log('Response: ' + JSON.stringify(response));

 if (angular.isDefined(response.config.headers['Response-Header'])) {
 var respHead = response.config.headers['Response-Header'];
 console.log('Response-Header: ' + respHead);
 nameService.responsename=respHead;
 }
 return response;
 }

 });

而且,spring 版本 4.1.6 @RestController 添加了标题。


@RestController
public class GreetingController {

 private static final String template ="Hello, %s!";
 private final AtomicLong counter = new AtomicLong();

 @RequestMapping("/greeting")
 public Greeting greeting(
 @RequestParam(value ="name", defaultValue ="World") String name,
 HttpServletResponse response,
 @RequestHeader("Request-Header") String headerName) {

//Sets our custom response header
 response.setHeader("Response-Header","Steve");

 return new Greeting(counter.incrementAndGet(),
 String.format(template, headerName));
 }
}

API代码 repo

用户界面代码 repo

感谢你的帮助 !

时间: 原作者:

0 0

问题是你的API GreetingController.java

更改问候语方法以返回ResponseEntity并使用 HttpHeaders,如下所示


@RequestMapping("/greeting")
 public ResponseEntity<Greeting> greeting(@RequestParam(value ="name", defaultValue ="World") String name, @RequestHeader("Request-Header") String headerName) {

 MultiValueMap<String, String> headers = new HttpHeaders();
//Sets our custom response header
 headers.add("Response-Header","Steve");
 return new ResponseEntity<Greeting>(new Greeting(counter.incrementAndGet(),String.format(template, headerName)), headers, HttpStatus.OK); 
 }

下面是我与邮差客户的邮件头响应


Content-Length → 2
Content-Type → text/plain;charset=UTF-8
Date → Wed, 27 May 2015 15:53:47 GMT
Response-Header → Steve
Server → Apache-Coyote/1.1

原作者:
...