设置请求cookie angular2 http post请求

前端之家收集整理的这篇文章主要介绍了设置请求cookie angular2 http post请求前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个登录服务执行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
        })

进行此调用时,cookie响应如下:

我看到我从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",options
            ).map( (responseData) => {
            this.apiResponse = responseData.json() as ApiResponse
            if (!this.apiResponse.Error) {
....

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

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

谢谢….

解决方法

试试这个登录
(...)
return this.http.post("http://localhost/request.PHP",{ withCredentials: true,headers: new Headers({
        'Content-Type': 'application/x-www-form-urlencoded'
    })
    }).map(...)

其他要求:

(...)
return this.http.post("http://localhost/request.PHP",{withCredentials: true}).map(...)

基本上,只需将withCredentials option设置为true即可.

猜你在找的HTML相关文章