简体   繁体   English

无法从 API 响应(Spring Boot Service)读取 Angular 中的 cookies(正在读取)- 无法读取 Z37A6259CC0C1DAE299A 的属性(正在读取)

[英]Not able to read cookies in Angular from API response (Spring Boot Service) - Cannot read properties of null (reading 'headers')

Service Code服务代码

public ResponseEntity<String> getSessionCookie() {
    logger.info("Get Cookies");
    var cookie1 = ResponseCookie.from("ASP.NET_SessionId_Wx", appConfig.getSessionId()).httpOnly(false).path("/").secure(false).build();
        var cookie2 = ResponseCookie.from("WX-XSRF-TOKEN", appConfig.getToken()).httpOnly(false).path("/").build();

    return ResponseEntity.ok().header(HttpHeaders.SET_COOKIE, cookie1.toString())
                .header(HttpHeaders.SET_COOKIE, cookie2.toString()).build();
    }

Angular Code Angular代码

Service服务

public getSession(): Observable<any> {  
     return this.http.get<any>('//example.com/getSessionCookie/', {withCredentials: true});
  }

Component零件

    this.ds.getSession().subscribe((res) => {
        console.log('Get Session Header: ', res.headers);
    })
  }

Able to view the cookies in Postman and Chrome Dev Tools (Network tab - Response Headers)能够在PostmanChrome 开发工具(网络选项卡 - 响应标头)中查看 cookies

Added CORS config to SprinBoot App将 CORS 配置添加到 SprinBoot 应用程序

public class CorsConfiguration implements WebMvcConfigurer
{
    @Override
        public void addCorsMappings(CorsRegistry registry) {              
registry.addMapping("/**").allowedOriginPatterns("*").allowedHeaders("*").allowCredentials(true)
                    .allowedMethods("GET", "POST", "PUT", "DELETE");
        }
}

I figured it out.我想到了。

The issue was with the 'Set-Cookie'.问题出在“Set-Cookie”上。 Angular is unable to read the 'Set-Cookie' header. Angular 无法读取“Set-Cookie”header。 Changed the header key to some other name and added the same in exposedHeaders as well.将 header 键更改为其他名称,并在exposedHeaders 中添加相同的名称。

Worked like a Charm:).像魅力一样工作:)。

Thanks.谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM