Home > Article > Web Front-end > How to Configure Axios to Automatically Include Cookies in Requests to an Express.js Server?
Problem Statement:
When making HTTP requests from a client to an Express.js server using Axios, cookies set on the client are not automatically sent in requests. As a result, the server-side code cannot access those cookies for authentication or other purposes.
To resolve this issue, the Axios library provides the withCredentials property. Setting it to true enables cross-site request forwarding (CORS) credentials, allowing Axios to include cookies in its requests.
axios.get(`some api url`, { withCredentials: true });
This property can be applied to individual Axios requests or set as a default for all requests:
// Force credentials for all Axios requests axios.defaults.withCredentials = true; // Use credentials for a specific Axios request instance const instance = axios.create({ withCredentials: true, baseURL: BASE_URL }); instance.get('/todos');
By setting withCredentials to true, CORS credentials are enabled, ensuring that cookies are automatically sent in Axios requests to the configured domain. This allows server-side code to access and utilize those cookies for session management, authentication, or any other necessary purpose.
The above is the detailed content of How to Configure Axios to Automatically Include Cookies in Requests to an Express.js Server?. For more information, please follow other related articles on the PHP Chinese website!