2016-10-27 71 views
7

我有一個登錄服務執行一個http請求(到php後端服務器)並返回一個cookie。登錄後,該cookie需要用於客戶端的所有進一步請求。設置請求cookies angular2 http發佈請求

login服務:

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 
     }) 

在這樣做時調用,cookie的反應是這樣的:
getcookie

我看到,我從在session_start的SESSION_ID(我的PHP服務器上)

我在做請求時:

searchExams(searchObject:SearchObject):Observable<any>{ 
     let headers = new Headers(); 
     headers.append('Content-Type', 'application/x-www-form-urlencoded',) 
     let options = new RequestOptions({ headers: headers, withCredentials: true}); 
     this.request.ServiceType = ServiceType.SearchExams; 
     this.request.SessionId = this.userSessionData.SessionId; 
     this.request.Compression = "no" 
     this.request.Parameters = searchObject; 
     let jsonRequest = JSON.stringify(this.request) 
     console.log(jsonRequest) 
     return this.http.post("http://localhost/request.php", "data="+ jsonRequest, options 
      ).map((responseData) => { 
      this.apiResponse = responseData.json() as ApiResponse 
      if (!this.apiResponse.Error) { 
.... 

我看到請求Cookie與我從服務器獲得的完全不同。此外,它始終是相同的PHPSESSID postrequest

我是否需要設置請求Cookie?怎麼樣? 我錯過了什麼?

感謝....

+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(...) 

基本上,只要使用withCredentialsoption設置爲true

+0

謝謝!的確是答案。 –

+0

非常感謝你! – donlys