angular 2 http withCredentials

2019-01-22 02:14发布

I'm am trying to use withCredentials to send a cookie along to my service but can't find out how to implement it. The docs say "If the server requires user credentials, we'll enable them in the request headers" With no examples. I have tried several different ways but it still will not send my cookie. Here is my code so far.

private systemConnect(token) {
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('X-CSRF-Token', token.token);
    let options = new RequestOptions({ headers: headers });
    this.http.post(this.connectUrl, { withCredentials: true }, options).map(res => res.json())
    .subscribe(uid => {
        console.log(uid);
    });
}

3条回答
迷人小祖宗
2楼-- · 2019-01-22 02:50

Starting with Angular 4.3, HttpClient and Interceptors were introduced.

A quick example is shown below:

@Injectable()
export class WithCredentialsInterceptor implements HttpInterceptor {

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        request = request.clone({
            withCredentials: true
        });

        return next.handle(request);
    }
}

constructor(
      private http: HttpClient) {

this.http.get<WeatherForecast[]>('api/SampleData/WeatherForecasts')
    .subscribe(result => {
        this.forecasts = result;
    },
    error => {
        console.error(error);
    });
查看更多
Emotional °昔
3楼-- · 2019-01-22 02:53

Try to change your code like this

let options = new RequestOptions({ headers: headers, withCredentials: true });

and

this.http.post(this.connectUrl, <stringified_data> , options)...

as you see, the second param should be data to send (using JSON.stringify or just '') and all options in one third parameter.

查看更多
兄弟一词,经得起流年.
4楼-- · 2019-01-22 02:54

Creating an Interceptor would be good idea to inject stuff into header across the application. On the other hand, if you are looking for a quick solution that needs to be done on a per request level, try setting withCredentials to true as below

const requestOptions = {
 headers: new HttpHeaders({
  'Authorization': "my-request-token"
 }),
 withCredentials: true
};
查看更多
登录 后发表回答