【问题标题】:How to use cookies on angular 4+ to make get and post如何在 Angular 4+ 上使用 cookie 来获取和发布
【发布时间】:2017-12-04 19:29:21
【问题描述】:

您能否提供一个示例或参考,说明如何在 angular4+ 上使用 cookie 执行 GET 和 POST?在 angularJS 上有文档,但在 Angular.io 上没有。 任何等效于此:Angular4+上的“//code.angularjs.org/X.Y.Z/angular-cookies.js” 在此先感谢

【问题讨论】:

    标签: angular post cookies get


    【解决方案1】:

    如果您使用的是新的 Angular 5,他们引入了称为 HttpInterceptor (https://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

    【讨论】:

    • 拦截器不是 5 独有的。它们出现在 4.3 中。
    【解决方案2】:

    我最终写了如下内容:

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

    以防其他人面临同样的问题。

    【讨论】:

    • 我认为 AllowAnyOrigin() 将 Access-Control-Allow-Origin 设置为 * 与 withCredentials: true set in frontend call 在我的情况下导致此异常:对​​预检请求的响应未通过访问控制检查:当请求的凭证模式为“包含”时,响应中的“Access-Control-Allow-Origin”标头的值不能是通配符“*”。
    猜你喜欢
    • 1970-01-01
    • 2017-05-11
    • 2017-06-22
    • 1970-01-01
    • 2018-01-31
    • 1970-01-01
    • 1970-01-01
    • 2017-12-29
    • 2018-09-25
    相关资源
    最近更新 更多