Why Isn\'t My Browser Setting Cookies from Cross-Origin Responses?

Mary-Kate Olsen
Release: 2024-11-17 07:08:03
Original
164 people have browsed it

Why Isn't My Browser Setting Cookies from Cross-Origin Responses?

Browser Refuses to Honor Set-Cookie Header from Cross-Origin Response

Problem:

An application struggles to set and retain an HTTP cookie sent from the backend to the front end.

Specifics:

  • The backend correctly sends the cookie in the response header.
  • The front end uses Axios to send requests, but the cookie is not being set locally.
  • The API router has the necessary headers and CORS settings to allow cookies.

Resolution:

The error lies in the placement of withCredentials in the Axios request configuration. withCredentials is a property of the request, not a request header. To resolve the issue, it should be moved from the headers object to the top-level configuration object.

Corrected Code:

const axiosAuth = axios.create({
  validateStatus: (status: number) => {
    return status >= 200 && status < 300;
  },
  headers: {
    Accept: `application/json`,
    'Content-Type': 'application/json',
  },
  withCredentials: true,
});
Copy after login

By using withCredentials: true in the configuration object, Axios will automatically handle the cross-origin cookie setting and retrieval.

The above is the detailed content of Why Isn\'t My Browser Setting Cookies from Cross-Origin Responses?. 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