私はangular2の "ヒーローのツアー"のチュートリアルを成功裏に終えました。それから、バックエンドとしてsymfony3、FosRestBundle、BazingaHateoasBundleに基づくAPIをビルドします。 ほとんどすべての機能が動作しますが、新しいアイテムの作成時には、新しく作成されたアイテムを読み込むためのレスポンスから「Location」ヘッダーを取得できません。私はaddHeroメソッドを呼んでいるときangular2/httpは201の応答ヘッダを取得します
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);
}
}
ので、新しいヒーローが作成され、201応答は体のない、しかし、Locationヘッダセットで返されます:
ここは私のヒーロー・サービスであります
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')
が応答からロケーションヘッダーを取得しなかったことです。 デバッグ後、res.headers
は2つのヘッダーCache-ControlとContent-Typeを提供しているようです。しかし、場所はありません。
新しく作成されたデータをレスポンス本体に追加することで問題を解決することも可能であることはわかっていましたが、実際にこれを解決する方法ではありません。
ありがとうございます!
'場所を貢献すべての人へ
感謝します。それはあなたの '応答オブジェクト'によって含まれていますか?そうであれば、何が問題なのですか? – micronyks
いいえ、私はレスポンスオブジェクトでそれを見つけられませんでした。私はこれが問題だと確信しています;)。しかし、私はどこでそれを探し求めなければならないのか分かりません。 – skroczek
この最後のスニペットはどのようにして得ましたか? – micronyks