symfony - angular2/http 获取 201 响应的位置 header

标签 symfony cors angular hateoas angular2-http

我成功完成了angular2“英雄之旅”入门教程。然后我构建了一个基于 symfony3、FosRestBundle 和 BazingaHateoasBundle 作为后端的 api。 现在几乎一切正常,但在创建新项目时,我无法从响应中获取“位置” header 以加载新创建的项目。

这是我的英雄服务:

import {Injectable} from "angular2/core";
import {Hero} from "./hero";
import {Http, Headers, RequestOptions, Response} from "angular2/http";
import {Observable} from "rxjs/Observable";
import "rxjs/Rx";

@Injectable()
export class HeroService {

    constructor(private _http:Http) {
    }

    private _apiUrl = 'http://tour-of-heros.loc/app_dev.php/api'; // Base URL
    private _heroesUrl = this._apiUrl + '/heroes';  // URL to the hero api


    getHeroes() {
        return this._http.get(this._heroesUrl)
            .map(res => <Hero[]> res.json()._embedded.items)
            .do(data => console.log(data)) // eyeball results in the console
            .catch(this.handleError);
    }

    addHero(name:string):Observable<Hero> {

        let body = JSON.stringify({name});

        let headers = new Headers({'Content-Type': 'application/json'});
        let options = new RequestOptions({headers: headers});

        return this._http.post(this._heroesUrl, body, options)
            // Hero is created, but unable to get URL from the Location header!
            .map((res:Response) => this._http.get(res.headers.get('Location')).map((res:Response) => res.json()))
            .catch(this.handleError)

    }

    private handleError(error:Response) {
        // in a real world app, we may send the error to some remote logging infrastructure
        // instead of just logging it to the console
        console.error(error);
        return Observable.throw(error.json().error || 'Server error');
    }

    getHero(id:number) {
        return this._http.get(this._heroesUrl + '/' + id)
            .map(res => {
                return res.json();
            })
            .do(data => console.log(data)) // eyeball results in the console
            .catch(this.handleError);
    }
}

因此,当我调用 addHero 方法时,会创建一个新的 Hero 并返回一个没有正文但设置了 Location header 的 201 响应:

Cache-Control: no-cache
Connection: Keep-Alive
Content-Length: 0
Content-Type: application/json
Date: Tue, 29 Mar 2016 09:24:42 GMT
Keep-Alive: timeout=5, max=100
Location: http://tour-of-heros.loc/app_dev.php/api/heroes/3
Server: Apache/2.4.10 (Debian)
X-Debug-Token: 06323e
X-Debug-Token-Link: /app_dev.php/_profiler/06323e
access-control-allow-credentials: true
access-control-allow-origin: http://172.18.0.10:3000

问题是,res.headers.get('Location') 没有从响应中获取 Location header 。 经过一些调试后,res.headers 似乎只提供了两个 header Cache-Control 和 Content-Type。但没有位置。

我知道也可以通过将新创建的数据添加到响应正文来解决问题,但这并不是我真正想要解决的方法。

提前致谢!

最佳答案

您应该使用 flatMap 运算符而不是 map 运算符:

return this._http.post(this._heroesUrl, body, options)
        .flatMap((res:Response) => {
          var location = res.headers.get('Location');
          return this._http.get(location);
        }).map((res:Response) => res.json()))
        .catch(this.handleError)

编辑

关于标题问题。

我认为您的问题与 CORS 有关。我认为预检请求应该在其响应中返回要在 Access-Control-Allow-Headers 中授权的 header 。类似的东西:

Access-Control-Allow-Headers:location

如果您在调用的服务器端,您可以使用要在客户端使用的 header 更新此 header (在您的情况下Location`)。

我调试了请求,特别是在实际执行请求并从 XHR 对象获取响应的 XhrBackend 类中。 header 未由代码返回:_xhr.getAllResponseHeaders()。就我而言,我只有 Content-Type 一个。

请参阅此链接:https://github.com/angular/angular/blob/master/modules/angular2/src/http/backends/xhr_backend.ts#L42 .

来自以下问题:

Cross-Origin Resource Sharing specification filters the headers that are exposed by getResponseHeader() for non same-origin requests. And that specification forbids access to any response header field other except the simple response header fields (i.e. Cache-Control, Content-Language, Content-Type, Expires, Last-Modified, and Pragma):

有关详细信息,请参阅此问题:

关于symfony - angular2/http 获取 201 响应的位置 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36280565/

相关文章:

angular - 为什么 angular 找不到 app.js 文件并抛出 404 错误?

symfony - 没有奏鸣曲媒体包的列表映射器中某个实体的奏鸣曲管理包预览图像

php - 在 Symfony 中使用非默认实体管理器自动映射

java - 从 ReactJS 访问 REST 服务时出现 CORS 问题

javascript - 将 Fetch 与授权 header 和 CORS 结合使用

jquery - 仅当有 header 时,CORS 请求才会在 Chrome 中失败

php - 在 Symfony 2 中使用注释时生成 url 的路由名称

mongodb - 使用 composer 为 Symfony2 设置 MongoDb

angular - npm/Angular 问题 : Could not resolve module @angular/core

angular - Ionic 2 - 如何重新计算滚动内容和固定内容的边距