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

原作者:
...