Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 replacement of $httpProvider.defaults.withCredentials

I have the exact same problem as this question but for Angular 2.

To sum up, when sending an HTTP request to another domain, the JSESSIONID cookie is not sent along even if CORS headers are correctly set up. The Angular 1.x solution is to set the following configuration:

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

However I can't find any replacement solution for Angular 2.

Any idea? Thanks!

like image 758
foch Avatar asked Nov 09 '22 00:11

foch


1 Answers

You need to extend 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 your http service

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

...

providers: [
  {
    provide: Http,
    useFactory: HttpServiceFactory,
    deps: [XHRBackend, RequestOptions]
  }
]
like image 177
kkl Avatar answered Nov 15 '22 06:11

kkl