我正在尝试编写一个具有独立后端(使用 Spring Boot 和 Spring Security 进行登录)和前端(ReactJS)的应用程序。现在,我正在努力在成功登录后访问安全端点。
我想要实现的目标:对安全端点进行 GET,例如“/books/all”。如果用户未登录,则返回 401。如果前端收到 401,则对 '/login' 进行 POST。然后我想要成功登录并能够成功获取到“/books/all”。
什么不起作用:最后一部分。我正在向 '/login' 发送 POST 并收到 200 GET。然后我再次调用“/books/all”并收到 GET 401。此外,我不再收到让我担心的 JSESSIONID cookie。
我的问题:如何解决这种行为?我相信它已连接到 JSESSIONID(服务器不发送有关用户成功登录的信息?)。
在前端,我使用 axios。
axios.get('http://localhost:8080/rest/book/anna/all')
.then(response => {
console.log('response rebuild');
console.log(response);
if (response.status === 401 && response.request.responseURL === 'http://localhost:8080/login') {
axios.post('http://localhost:8080/login', 'username=c&password=d')
.then(response => {
console.log('response 2');
console.log(response);
})
.catch(error => {
console.log('error');
console.log(error);
})
}
})
.catch(error => {
console.log('error 2');
console.log(error);
axios.post('http://localhost:8080/login', 'username=c&password=d')
.then(response => {
console.log('response 2');
console.log(response);
axios.get('http://localhost:8080/rest/book/anna/all') …Run Code Online (Sandbox Code Playgroud)