【问题标题】:Setting request cookies angular2 http post request设置请求cookie angular2 http post请求
【发布时间】:2017-03-10 06:35:00
【问题描述】:

我有一个登录服务,它执行一个 http 请求(到一个 php 后端服务器)并返回一个 cookie。登录后,此 cookie 需要在客户端完成的所有进一步请求中使用。

登录服务:

   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", "data="+ jsonRequest, options
            ).map( (responseData) => {
            this.apiResponse = responseData.json() as ApiResponse
            if (!this.apiResponse.Error) {
....

我看到请求 cookie 与我从服务器获得的完全不同。此外,它始终是相同的 PHPSESSID

我需要设置请求cookie吗?如何? 我错过了什么?

谢谢....

【问题讨论】:

标签: angular cookies http-post session-cookies


【解决方案1】:

试试这个登录:

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

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

【讨论】:

  • 谢谢!确实是答案。
  • 在 ionic-angular 3.9.2 上为我工作。非常感谢!网络上的其他几个地方都提出了这个问题,但没有回答。我会将这些问题指向这个答案。
猜你喜欢
  • 2017-12-22
  • 2016-10-15
  • 2016-05-14
  • 2017-03-12
  • 1970-01-01
  • 2016-01-10
  • 2017-10-07
  • 2017-03-29
  • 2015-11-12
相关资源
最近更新 更多