foch
foch

Reputation: 1059

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!

Upvotes: 6

Views: 3886

Answers (2)

kkl
kkl

Reputation: 173

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]
  }
]

Upvotes: 1

SerLight Serafimov
SerLight Serafimov

Reputation: 1

When you using Http service from import { Http,Response, Headers } from '@angular/http' you can set 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();
            });;           
}

Upvotes: 0

Related Questions