首页 > 解决方案 > 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 :

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?

标签: vue.jshttpaxiosfetch

解决方案


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.


推荐阅读