withCredentials in cross domain request dosn't work
Problem
Context - axios version: v0.18.0, v.0.17.0 - Environment: e.g.: Firefox 52.9.0 Linux, Chrome 67.0.3396.99 Linux Problem It looks, that Axios is unable to send cookie in request to another domain. I've two app: frontend on local computer, port 8080 backend on local computer, port 9000 In frontend I've defined backend as: `http://127.0.0.1:9000`. In my JavaScript code I have service: [code block] When I open my frontend as: `http://127.0.0.1:8080` (frontend and backend are in the same domain 127.0.0.1, only port is different), everything is ok, cookie is present in request headers. But when I open my frontend as `http://localhost:8080` cookie is missing in request headers. It's GET request, and there no preflight request, so I would expect, that cookie will be added to request. I've attached screenshoots Correct request with cookie (the same domain): Incorrect request without cookie (cross domain):
Unverified for your environment
Select your OS to check compatibility.
1 Fix
Enable Cross-Domain Cookies for Axios Requests
The issue arises because cookies are considered to be tied to the domain and port. When accessing the frontend via 'http://localhost:8080', it is treated as a different origin than 'http://127.0.0.1:8080', causing the browser to block the cookies from being sent in cross-origin requests. This is due to the Same-Origin Policy enforced by browsers.
Awaiting Verification
Be the first to verify this fix
- 1
Update Axios Configuration
Ensure that the Axios instance is configured to include credentials in cross-origin requests by setting the 'withCredentials' property to true.
javascriptaxios.defaults.withCredentials = true; - 2
Set CORS Headers on Backend
Modify the backend server to include CORS headers that allow credentials to be sent. This typically involves setting 'Access-Control-Allow-Origin' to the frontend URL and 'Access-Control-Allow-Credentials' to true.
javascriptres.setHeader('Access-Control-Allow-Origin', 'http://localhost:8080'); res.setHeader('Access-Control-Allow-Credentials', 'true'); - 3
Use Consistent Domain in Frontend
Ensure that you access the frontend using the same domain format. Either use 'http://127.0.0.1:8080' or 'http://localhost:8080' consistently across both frontend and backend to avoid cross-origin issues.
- 4
Check Browser Settings
Verify that the browser settings allow cookies and that there are no extensions or privacy settings blocking cookies from being sent in cross-origin requests.
Validation
After implementing the changes, test the frontend by accessing it via 'http://localhost:8080' and check the network request headers in the browser's developer tools to confirm that the cookies are being sent with the requests to the backend.
Sign in to verify this fix
Environment
Submitted by
Alex Chen
2450 rep