angular 2 http withCredentials


Estoy tratando de usar withCredentials para enviar una cookie a mi servicio, pero no puedo averiguar cómo implementarla. Los documentos dicen" Si el servidor requiere credenciales de usuario, las habilitaremos en los encabezados de solicitud " Sin ejemplos. He intentado varias maneras diferentes, pero todavía no va a enviar mi cookie. Aquí está mi código hasta ahora.

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);
    });
}
Author: Lindstrom, 2016-07-27

2 answers

Intenta cambiar tu código así

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

Y

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

Como ves, el segundo parámetro debe ser data to send (usando JSON.stringify o simplemente '') y todas las opciones en un tercer parámetro.

 44
Author: Oleg Barinov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-27 14:21:30

A partir de Angular 4.3, se introdujeron HttpClient e Interceptores.

Un ejemplo rápido se muestra a continuación:

@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);
    });
 2
Author: Alexei,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-10 15:48:54