vue.js - Set-Cookie not accessible through axios or fetch
问题描述
I am building a web application with a go backend and a vue.js frontend. I want to do a simple sign in form in which I send the sign in request from a method of my component with Axios (or fetch) and get in response a JSON object of the user and a session token in the cookie to be stored and reused in future requests to the server.
The code of my components method :
class LoginComponent extends Vue {
sendLogin (): void {
axios.post<User>('http://192.168.1.227:8080/signin', body)
.then(res => console.log('Axios Response :', res)
.catch(err => console.error('Axios Error :', err))
}
}
The part of the code of the go server : go API with the headers : go headers
the front and backend are on different IP addresses in a local network and they communicate through HTTP.
The problem that I faced is that when receiving the response after the post request to login I don't have access to the cookie that has been set by the server. When I use Axios to analyze the response the cookie isn't in the headers whereas when I look at the network logs in the browser, the cookie is in the headers but it is not saved and it is not sent when I do another request.
Also, the only header that is visible with Axios is Content-Type : application/json; charset=UTF-8
I tried many things to be able to see this cookie but it doesn't work :
- adding
{ withCredentials: true }
to the axios request oraxios.defaults.withCredentials = true
to the axios instance only stops the request because of CORS. - changing all the Access-Control headers to
"*"
didn't change anything - using
{ auth: { username: 'foo', password: 'bar' } }
in the axios options instead of the body
The only thing that worked and automatically saved the cookie was to send the request via the attributes of the form html tag, like so :
<form method="POST" action="http://192.168.1.227/signin">
...
</form>
But this way I am redirected to the JSON response object and not to one of my routes from vue-router and I can't access the User object in my app.
Is there any way that my problem can be solved?
解决方案
Ok so the comment of Зелёный was the answer.
I needed the go server to set Access-Control-Allow-Origin: http://192.168.1.218:8080
(the address of the frontend) and then configure axios with { withCredentials: true }
to be able to automatically store the cookie. Although I still don't see it when I do a console.log on the axios response, it is successfully stored and reused for each call to the server.
推荐阅读
- openid-connect - Keycloak-Gatekeeper 在针对外部 OIDC 提供者进行身份验证时不会填充角色或组
- r - 如何编写具有条件查找功能的顺序 for 循环
- python - 给定字典中的键,提取 x 个先前的键值对
- c# - 无法加载文件或程序集 Nuget 包
- ffmpeg - ffmpeg 可以将元数据/ID3 从 FLAC 复制到 MP3 吗?
- arrays - 如何在列表中创建列表,使用来自一个向量的元素,在 r
- database - YugaByte DB 中的滚动升级 - 有可能吗?
- node.js - 未捕获的错误:模块“DropdownModule”导入的意外值“未定义”
- r - 如何修复 R 中的“在缓存中发现多个类“xts”消息?
- python - 如何将python列表传递回C程序