在底部查看更新。 我有一个小的REST API,该API带有弹簧靴和一个角(18)前端。 我想要的是从后端发送一个cookie。当我从前端到后端再打电话时,我希望将cookie发送到后端。 后端在端口8080和端口4200上运行。我在stackoverflow上看到了很多答案,并试图遵循许多教程和博客。 cookie用于识别客户端。我不希望会话cookie或cookie来确保我的服务,这是未来的任务。 我的REST API具有注释。
首先称为en end endpoint,称为getNewid。@RestController, @RequestMapping("/api") and @CrossOrigin(origins = "*", allowedHeaders = "*", methods = { RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE })
致电UTIL类生成新的cookie。
@GetMapping("/getnewid")
public String getNewID(HttpServletRequest request, HttpServletResponse response,
@CookieValue(value = Util.CLIENT_ID_COOKIE_NAME, defaultValue = "") String cookieValue)
throws CabinException {
Cookie cookie = Util.getNewID(request.getRemoteAddr(), request.getHeader("User-Agent"), cookieValue);
response.addCookie(cookie);
response.setStatus(200);
return cookie.getValue();
}
如果我直接在firefox中调用端点,我会用“正确”主机获得cookie。 如果我从Angular应用中调用端点,我是“错误的”主机。
以下内容来自Angular Service和调用Service
的代码
String tmpCookieClientID = UUID.randomUUID().toString();
Cookie clientIDCookie = new Cookie("cabinCTRLclientID", tmpCookieClientID);
clientIDCookie.setDomain("localhost");
clientIDCookie.setMaxAge(60 * 60 * 24 * 365);
return clientIDCookie;
getNewKey(): Observable<string> {
return this.httpClient.get<string>(this.baseURL + "getnewid");
}
对任何帮助都非常感谢。
update
我在响应标题中看到cookie已返回,但由于某种原因,它没有设置在浏览器中。这是来自Firefox的。我在铬中看到相同的行为。
I将CORS配置移至tomcat web.xml。没有更改,cookie是在请求中发送的,但未在浏览器中设置。
当我打电话给Spring Boot Service时,我“手动”添加了cookie。我使用了NGX-Cookie-Service的cookieservice。 getNewKey() {
this.subs.add(this.clientService.getNewKey().subscribe(key => console.log(key))
);
}