设置请求cookie angular2 http post请求

Man*_*979 7 cookies http-post session-cookies angular

我有一个登录服务,执行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
        })
Run Code Online (Sandbox Code Playgroud)

执行此调用时,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) {
....
Run Code Online (Sandbox Code Playgroud)

我看到请求cookie与我从服务器获得的cookie完全不同.而且它总是相同的PHPSESSID postrequest

我需要设置请求cookie吗?怎么样?我错过了什么?

谢谢....

AAr*_*ias 18

试试这个登录:

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

其他要求:

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

基本上,只需使用withCredentials 选项设置true.