In a React application integrated with a Go server, the server attempts to set a cookie during the login response. However, the cookie is not being saved by the browser, despite it being returned in the network tab's response.
The provided code snippets indicate that:
The http.SetCookie() function is used to add the cookie to the response with the following settings:
Screenshots from the network tab show that the cookie is indeed being sent back in the response headers.
The key to solving this issue lies in the Fetch API's credentials flag. When making a fetch request that anticipates a cookie in the response, it is essential to set credentials: "include".
fetch(`${url}/login`, { method: "POST", headers: { "Content-Type": "application/json", }, credentials: "include", // This line has been added body: JSON.stringify({ email: userDetails.email, password: userDetails.password, }), }).then((response) => { ...
By setting credentials to "include", the browser understands that it should accept and store the cookie included in the response. This configuration ensures that the browser correctly saves the cookie and makes it available for subsequent requests.
The above is the detailed content of Why Doesn't My Browser Store Cookies Set by My Go Server in a React App?. For more information, please follow other related articles on the PHP Chinese website!