2017-12-04 4 views

答えて

0

私のようなものを書いてしまったが、以下:

public postSomethingToServer(myUrl: string): Observable<any> { 
    var body = `{"username":"ddd","password":"ddd"}`; 
    const headers = new Headers(); 
    headers.append('Content-Type', 'application/json'); 
    let options = new RequestOptions({ headers: headers, withCredentials: true }); 
    return this.http.post(myUrl, body, options) 
     .map((response) => { 

     return response.json(); 
     }) 
     .catch(this.handleError); 
    } 

それが必要とされたリクエストにクッキーを送信するにはRequestOptionsクラスに渡されたオブジェクト内の(withCredentials:true)クライアントとサーバが他の人が同じ問題に直面している場合

app.UseCors(config => 
       config.AllowAnyOrigin()      
         .AllowCredentials()); 

CORS

を構成するために必要な異なるサーバー上で実行されている場合は、ASPネットコアの

はアプリ。

2

で おかげであなたは、彼らがHttpInterceptorhttps://angular.io/guide/http#intercepting-all-requests-or-responsesと呼ばれるものが導入された新しい角度5を使用している場合)

あなたができることは、あなたのクッキーを取得してそれに応じて処理するインターセプタを作成することです。あなたはまた、クッキーを処理するために、次のようにライブラリを使用することができます

import {Injectable} from '@angular/core'; 
import {HttpEvent, HttpInterceptor, HttpHandler, HttpRequest} from '@angular/common/http'; 

    function getCookie(name) { 
    const splitCookie = cookie.split(';'); 
    for (let i = 0; i < splitCookie.length; i++) { 
     const splitValue = val.split('='); 
     if (splitValue[0] === name) { 
     return splitValue[1]; 
     } 
    } 
    return ''; 
    } 

    @Injectable() 
    export class AuthInterceptor implements HttpInterceptor { 
     constructor(private auth: AuthService) {} 

     intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { 
     // Get the auth header from the service. 
     const authHeader = getCookie('auth'); 
     // Clone the request to add the new header. 
     const authReq = req.clone({headers: req.headers.set('Authorization', authHeader)}); 
     // Pass on the cloned request instead of the original request. 
     return next.handle(authReq); 
     } 
    } 

https://github.com/salemdar/ngx-cookie

+1

インターセプタは5に限定されません。4.3に登場しました。 – estus

関連する問題