'Axios - cross domain cookies
I have two applications (backend and frontend) running on local computer (frontend - Vue app on port 8080, backend - Scala app on port 9000)
I'm trying to send request to backend using Axios with cookie, but it works only, if both are running on the same domain:
It's working (cookie is present in API request):
backend address: http://127.0.0.1:9000/api/systems
frontend (in browser): http://127.0.0.1:8080
It doesn't work (request doesn't contain cookie):
backend address: http://127.0.0.1:9000/api/systems
frontend (in browser): http://localhost:8080
My frontend snippet with request:
const BASE_URL = appConfig.API_URL + '/api';
axios.defaults.withCredentials = true;
axios.get(BASE_URL + '/systems');
I think CORS are configured correctly:
play.filters.cors {
allowedOrigins = ["http://localhost:8080", "http://127.0.0.1:8080"]
supportsCredentials = true
allowedHttpMethods = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]
}
Solution 1:[1]
You need to set header in the response:
Access-Control-Allow-Headers: Set-Cookie
In express on node.js it's go like this:
res.setHeader('Access-Control-Allow-Headers', 'Set-Cookie')
Solution 2:[2]
try this on the backend:
const allowedOrigins = ['localhost',"http://localhost:8080", "http://127.0.0.1:8080","http://localhost:8080/"];
var corsOptions = {
origin: function (origin, callback) {
if (allowedOrigins.indexOf(origin) !== -1) {
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
console.log("------")
console.log("origin",origin)
}
},
credentials: true,
}
Solution 3:[3]
Different ports are considered cross-domain so it's likely not an issue with your CORS setting since in your first example the cross-domain request works. My guess is it's likely something to do with how your front-end treats localhost
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Yinon Yehuda Shisha |
Solution 2 | Govind S Kåtýurä |
Solution 3 | Noam |