I have a PHP Script which successfully returns some simple Headers as well as a set-cookie header if called directly in the browser (or by postman). I can read the response-
In my case, the network panel showed that the response had the 'Set-Cookie' header, but in axios the header wouldn't show up, and the cookie was being set.
For me, the resolution was setting the Access-Control-Expose-Headers
header.
Explanation:
From this comment on an issue in the axios repository I was directed to this person's notes which led me to set the Access-Control-Expose-Headers header -- and now the cookie is properly setting in the client.
So, in Express.js, I had to add the exposedHeaders
option to my cors middleware:
const corsOptions = {
//To allow requests from client
origin: [
"http://localhost:3001",
"http://127.0.0.1",
"http://104.142.122.231",
],
credentials: true,
exposedHeaders: ["set-cookie"],
};
...
app.use("/", cors(corsOptions), router);
It was also important that on the axios side I use the withCredentials
config in following axios requests that I wanted to include the cookies.
ex/
const { data } = await api.get("/workouts", { withCredentials: true });
For me is working adding {withCredentials: true} like this:
axios
.post(url, {
foo: foo,
baz: baz,
}, {withCredentials: true})
.then(.............
This may not apply to your situation, but I had the same problem using axios in this standalone nodejs script.
const config = {
url: 'https://remote.url/login',
method: 'post',
headers: {
'content-type': 'application/x-www-form-urlencoded',
},
data: qs.stringify({
'email': username,
'password': pwd
})
}
axios(config).then(res => {
console.log(res.headers);
}).catch(err => {
console.log(err);
})
This returned http status 200 without set-cookie
in the headers. With curl the header was correctly retrieved, but the status code was 302
After adding the following config options to axios:
maxRedirects: 0,
validateStatus: function (status) {
return status <= 302; // Reject only if the status code is greater than 302
},
I received the set-cookie
in axios in the response.header.
{
server: 'nginx/1.16.1',
date: 'Fri, 27 Dec 2019 16:03:16 GMT',
'content-length': '74',
connection: 'close',
location: '/',
'set-cookie': [
'cookiename=xxxxxxxxxxxxxxxxxxxxx; path=/; expires=Sat, 26-Dec-2020 16:03:16 GMT'
],
status: '302',
'x-frame-options': 'DENY'
}
Without maxRedirects: 0
I received the html of the homepage of the remote url I used.
Without validateStatus
I received the set-cookie
header in the err.response.headers
object.
probably cookie is 'httpOnly', which means client side javascript can not read it. Therefore it is not showing in chrome cookie section. test the same request in mozilla, header will show up.