如何在角4+上使用cookies来获取和发布

时间:2017-12-04 19:29:21

标签: angular post cookies get

您是否可以提供有关如何在angular4 +执行GET和POST时使用Cookie的示例或参考?在angularJS上有记录但在Angular.io上没有。 任何等价于:Angular4 +上的“//code.angularjs.org/X.Y.Z/angular-cookies.js” 提前致谢

2 个答案:

答案 0 :(得分:6)

如果你正在使用新的Angular 5,他们引入了名为HttpInterceptorhttps://angular.io/guide/http#intercepting-all-requests-or-responses

的内容

你可以做的是创建一个拦截器来获取你的cookie并相应地处理它。

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

您还可以使用此类库来处理Cookie: https://github.com/salemdar/ngx-cookie

答案 1 :(得分: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);
  }

要在请求中发送cookie,需要在传递给RequestOptions类的对象中使用(withCredentials:true)。

对于ASP Net Core应用程序,如果客户端和服务器在配置CORS所需的不同服务器上运行

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

如果其他人遇到同样的问题。