我有一个登录服务,执行http请求(到php后端服务器)并返回一个cookie。登录后,需要在客户端进行的所有进一步请求中使用此cookie。
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
})
我看到我从session_start(在我的php服务器上)获取session_id
我在做请求时:
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与我从服务器获得的cookie完全不同。而且它总是相同的PHPSESSID
我是否需要设置请求cookie?怎么样? 我错过了什么?
...谢谢
答案 0 :(得分:18)
尝试登录:
sessionStorage
其他要求:
(...)
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(...)
option设置为withCredentials
。