2016-10-27 7 views
7

私は(PHPバックエンドサーバーへの)HTTPリクエストを実行し、クッキーを返すログインサービスを持っています。ログイン後、このクッキーは、クライアントが行った以降のすべての要求で使用する必要があります。要求のクッキーを設定するangular2 http投稿のリクエスト

loginservice:この呼び出しを行うとき

login(userCredentials:UserCredentials):Observable<any> {  
     this.request.ServiceType = "Connect" 
     this.request.SessionId = "sessionlessrequest" 
     this.request.Compression = "no" 
     this.request.Parameters = userCredentials; 
     let jsonRequest = JSON.stringify(this.request) 
     return this.http.post("http://localhost/request.php", "data="+ jsonRequest, 
      { headers: new Headers({ 
       'Content-Type': 'application/x-www-form-urlencoded' 
      }) 
      }).map((responseData) => { 
      this.apiResponse = responseData.json() as ApiResponse 
      if (!this.apiResponse.Error) { 
       this.sessionData.next(this.apiResponse.Data as UserSessionData) 
       this.sessionData.asObservable().share 
      } else { 
       console.log(this.apiResponse.ErrorMessage) 
      } 
      return null 
     }) 

、クッキーの応答は、このようなものです:
getcookie

私は私が(私のPHPサーバー上)のsession_startからSESSION_IDを取得していることがわかり

Iリクエストを行うとき:

リクエストのCookieは、サーバーから取得したCookieとまったく異なっています。また、常に同じですPHPSESSID postrequest

リクエストクッキーを設定する必要がありますか?どうやって? 私は何が欠けていますか?

おかげで....

+2

これは参考になるかもしれません:http://stackoverflow.com/questions/35602866/how-to-send-cookie-in-request-header-for-all-the-requests-in-angularjs2 – RomanHotsiy

答えて

15

は、ログインのためにこれを試してみてください:

(...) 
return this.http.post("http://localhost/request.php", "data="+ jsonRequest, 
    { withCredentials: true, 
     headers: new Headers({ 
     'Content-Type': 'application/x-www-form-urlencoded' 
    }) 
    }).map(...) 

そして、他の要求:

(...) 
return this.http.post("http://localhost/request.php", "data="+ jsonRequest, 
         {withCredentials: true}).map(...) 

基本的には、ちょうどtruewithCredentialsoptionセットを使用します。

+0

ありがとうございます!確かに答え。 –

+0

ありがとう! – donlys

関連する問題