angular 2 http withCredentials angular 2 http withCredentials angular angular

angular 2 http withCredentials


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.


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);    });

Remember to provide the interceptor to your app module, as the article says:

In order to activate the interceptor for our application we need to provide it to the main application module AppModule in file app.module.ts:

Your @NgModule will need to include this in its providers:

  ...  providers: [{    provide: HTTP_INTERCEPTORS,    useClass: WithCredentialsInterceptor,    multi: true  }],  ...


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