如何在Angular 4+中使用cookies进行GET和POST请求

3

你能提供一个示例或参考代码来说明如何在Angular4+上使用cookie执行GET和POST操作吗?在AngularJS上有相关文档,但在Angular.io文档中没有。是否有类似于"//code.angularjs.org/X.Y.Z/angular-cookies.js"这样的等效方案可以在Angular4+中使用? 谢谢。

2个回答

8
如果您正在使用新的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);
      }
    }

你可以使用这样的库来处理cookies: https://github.com/salemdar/ngx-cookie

2
拦截器不仅限于5,它们也出现在4.3中。 - Estus Flask

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

如果其他人面临相同的问题。


1
我认为在前端调用中,将AllowAnyOrigin()与withCredentials:true相结合时,将Access-Control-Allow-Origin设置为会导致我的情况出现异常:响应预检请求未通过访问控制检查:当请求的凭据模式为“include”时,响应中的“Access-Control-Allow-Origin”头的值不能是通配符“”。 - Janne Harju

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接