我正在編寫Angular 2(不是JS中的大專家)和Rails 4.2之間的一些集成。在Rails方面,我使用設計進行身份驗證。事情是當我要求登錄用戶時,Set-Cookie
標題返回響應。但是,然後,當我試圖請求任何驗證所需的資源Cookie
標頭的值爲"Set-Cookie=null"
(如沒有值Set-Cookie
?)。下面是它是如何做:Angular 2 cookie身份驗證
session.service.ts
@Injectable()
export class SessionService{
private headers = new Headers({'Content-Type': 'application/json', 'Accept': 'application/json'})
private createSessionUrl = 'http://localhost:3002/users/sign_in';
constructor(
private http: Http
) { }
create(email: string, password: string): Promise<User>{
return this.http.post(this.createSessionUrl, JSON.stringify({user:{email: email, password: password}}),
{ headers: this.headers })
.toPromise()
.then(response => response.json() as User)
.catch(this.handleError)
}
private handleError(error: any): Promise<any> {
return Promise.reject(error.message || error);
}
}
statistics.service.ts
import { Injectable } from '@angular/core';
import { Headers, Http, RequestOptions } from '@angular/http';
import { Statistics } from '../models/statistics.models'
import 'rxjs/add/operator/toPromise';
@Injectable()
export class StatisticsService{
private headers = new Headers({'Content-Type': 'application/json', 'Accept': 'application/json'})
private statisticsUrl = 'http://localhost:3002/statistics';
constructor(
private http: Http
) {}
show(): Promise<Statistics>{
let options = new RequestOptions({ headers: this.headers, withCredentials: true });
return this.http.get(this.statisticsUrl, options)
.toPromise()
.then(response => response.json() as Statistics)
.catch(this.handleError)
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
}
據我所知,let options = new RequestOptions({ headers: this.headers, withCredentials: true });
應包括要求適當的Cookie。
如果有任何額外的信息需要,請在評論中寫。