Angular2 replacement $ httpProvider.defaults.withCredentials

I have the same issue as this question, but for Angular 2.

To summarize, when sending an HTTP request to another domain, the JSESSIONID cookie is not sent, even if the CORS headers are configured correctly. Angular 1.x solution should install the following configuration:

.config(function ($routeProvider, $httpProvider) {
    $httpProvider.defaults.withCredentials = true;
    //rest of route code

However, I cannot find a replacement solution for Angular 2.

Any idea? Thanks!

+4
source share
2 answers

You need to extend the default Http service and set withCredentials to true

http.service.ts

import { Injectable } from '@angular/core';
import { Headers, Http, Request, RequestOptions, Response, XHRBackend } from '@angular/http';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class HttpService extends Http {
  constructor(backend: XHRBackend, options: RequestOptions) {
    super(backend, options);
  }

  request(url: string | Request, options?: any): Observable<Response> {
    if (typeof url === 'string') {
        if (!options) {
            options = {headers: new Headers()};
        }
        options.withCredentials = true;
    } else {
        url.withCredentials = true;
    }

    return super.request(url, options);
  }
}

http.service.factory.ts

import { RequestOptions, XHRBackend } from '@angular/http';
import { HttpService } from './http.service';

export function HttpServiceFactory(backend: XHRBackend, defaultOptions: RequestOptions) {
  return new HttpService(backend, defaultOptions);
};

and in your module file you need to replace the http service

import { HttpServiceFactory } from './http.service.factory';
import { Http, RequestOptions, XHRBackend } from '@angular/http';

...

providers: [
  {
    provide: Http,
    useFactory: HttpServiceFactory,
    deps: [XHRBackend, RequestOptions]
  }
]
+1
source

Http {Http, Response, Headers} '@ angular/http', withCredentials: true;

post(params:string, obj:any): Observable<any> {
    let headers = new Headers();
    headers.append("content-type", "application/json"); 
    return this.http.post(this.apiUrl + params, JSON.stringify(obj), { headers: headers, withCredentials: true })
        .map((response : Response)=>{
                return response.json();
            });;           
}
0

Source: https://habr.com/ru/post/1619228/


All Articles