Why Won\'t My Browser Store Cookies from Cross-Origin Requests?

Linda Hamilton
Release: 2024-11-24 20:49:18
Original
237 people have browsed it

Why Won't My Browser Store Cookies from Cross-Origin Requests?

Browser Refuses to Store Cookies in Cross-Origin Requests

Problem Description:

A React application using a Go server encounters difficulties in storing a cookie sent in the login request response despite successfully setting it. The cookie is visible in the network tab, but the browsers (Chrome and Firefox) do not save it.

Root Cause and Solution:

Upon further investigation, it was discovered that the missing ingredient was the 'credentials' flag in the fetch request. Setting 'credentials: "include"' allows the browser to handle and store cookies received in the response. The corrected fetch request is:

fetch(`${url}/login`, {
    method: "POST",
    headers: {
        "Content-Type": "application/json",
    },
    credentials: "include", // This here
    body: JSON.stringify({
        email: userDetails.email,
        password: userDetails.password,
    }),
}).then((response) => { ...
Copy after login

Additional Precautions:

  • Ensure that the server is configured with the CORS handler to allow cross-origin requests with credentials.
  • For custom CORS configurations, set 'AllowCredentials' to true.
  • Verify the response headers to confirm that the cookie is being set as expected.

The above is the detailed content of Why Won\'t My Browser Store Cookies from Cross-Origin Requests?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template