首页 > 解决方案 > Angular 无法读取后端发送的 cookie

问题描述

我想使用 JAX-WS 和 Jersey 从我的后端发送一个简单的 cookie 到我的 Angular 网络客户端,但 Chrome 无法读取或设置 cookie。

    @GET
    @Path("/cookie")
    @Produces(MediaType.TEXT_PLAIN)
    public Response getId(@CookieParam("session") String inp)
    {
        if (!keys.contains((inp))) {
            String cipher = randomize();
            keys.add(cipher);
            return Response.ok().cookie(new NewCookie("session", cipher)).build();
        }
        return Response.ok().build();
    }

这就是我在后端的做法

private httpHeaders = new HttpHeaders()
        .set('Accept', 'text/plain')
        .set('Content-Type', 'text/plain');

    private options = {
        headers: this.httpHeaders
    };

  constructor(private httpClient: HttpClient) { }

  getId(){
    return this.httpClient.get(this.apiUrl+'session/cookie', this.options);
  }

这就是我在客户端管理它的方式。

标签: angulargoogle-chromejerseyjax-ws

解决方案


First you can double check wether if the API is providing data accordingly to the request with POSTMAN call. If So you can come to conclusion that there is nothing wrong in the API.

Secondly I see inside your getId() method while you are using the httpClient you doest actually subscribe the to the get request.

You need to subscribe to the request in order to fetch values from the API and inititate the request.

getId(){
    return this.httpClient.get(this.apiUrl+'session/cookie', 
          this.options).subscribe((token)=>{
           console.log(token)
      });
  }

推荐阅读