【发布时间】:2020-10-04 10:01:17
【问题描述】:
所以我在后端编写了一段代码,通过 HttpServletResponse 设置 cookie。但是,无论我做什么,cookie 都不会存储在浏览器中。
我试过了-
- 将所有内容设置为 127.0.0.1
- 将 /etc/hosts 设置为二级域
- 在获取请求中设置凭据
- 设置 cookie 的最大期限
- SO 推荐的其他答案
这里是 index.html
<html>
<head>
<title>Cookie Test</title>
</head>
<body>
<script>
async function getCookie() {
let response = await fetch("http://127.0.0.1:8080/getCookie");
let data = await response.text();
console.log(data);
}
getCookie();
</script>
</body>
</html>
这是我的控制器-
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@CrossOrigin(origins="*")
public class Controller {
@GetMapping("/getCookie")
public String getCookie(HttpServletResponse response) {
Cookie cookie = new Cookie("name", "Test123");
cookie.setPath("/");
response.addCookie(cookie);
return "Cookie added";
}
}
请求被发送,没有错误。但是,每当我检查 cookie 时,它从未设置过。我也尝试了其他 SO 问题/答案所推荐的方法,但没有任何效果。此外,当我访问 Spring/controller 页面本身而不是 Apache/index.html 页面时,cookie 被设置。但是,当访问 Apache/index.html 页面时,cookie 没有设置。
【问题讨论】:
标签: javascript spring spring-boot spring-mvc cookies