2017-12-04 5 views

답변

0

나는 다음과 같은 것을 쓰고 결국이 쿠키를 처리하기 위해 같은

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

는 또한 라이브러리를 사용할 수 있습니다 RequestOptions 클래스에 전달 된 객체의 (withCredentials : true) 클라이언트와 서버가 다른 사람이 같은 문제에 직면 경우

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

CORS

을 구성하는 데 필요한 서로 다른 서버에서 실행하는 경우 ASP 닷넷 코어

앱.

2

새 각도 (5)들이라는 것을 도입 사용하는 경우 HttpInterceptor (https://angular.io/guide/http#intercepting-all-requests-or-responses)

당신이 할 수있는 것은 당신의 쿠키를 얻고 그에 따라 처리하는 인터셉터를 만드는 것입니다.

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

그것이 필요했다 요청에 쿠키를 전송하려면 : https://github.com/salemdar/ngx-cookie

+1

인터셉터는 5가 아닙니다. 4.3에 나타났습니다. – estus

관련 문제