middleware:
this.express.use(cors({
exposedHeaders: config.corsHeaders,
credentials: true
}));
this.express.use(session({
secret: 'secret',
resave: false,
saveUninitialized: true,
cookie: { maxAge: 600000000 }
}));
route:
this.router.get('/session', ({session, query}, res) => {
session.word = query.word;
session.obj = {
word: query.word
};
session.arr = [ { word: query.word}];
session.save((err) => {
if (!err) res.json({ success: 'success: '+ query.word });
});
});
this.router.get('/session/get', ({session, query}, res) => {
res.json({ session });
});
when I try this on Chrome or Postman, Everything work properly and I got session data from /session/get.
but when I used this by axios, express doesn't store any session, I got only a cookie object
Hi @dumpsayamrat I'm not familiar with axios. Can you provide some code and instructions for using axios that reproduces the issue?
It's just a simple code like this.
<div class="form-group">
<button id="theBtn">Click me to set session</button>
</div>
<div class="form-group">
<button id="theBtn2">Click me to get the session</button>
</div>
$('#theBtn').on('click', function() {
axios.get('http://localhost:8080/session?word=bananaToU').then(function(response) {
console.log(response.data); // { success: 'success: bananaToU' }
})
})
$('#theBtn2').on('click', function() {
axios.get('http://localhost:8080/session/get').then(function(response) {
console.log(response.data); // { session: { cookie: {...} } } -> I expected to get the session that's I provide in above event but there's nothing.
})
})
Both codes are in same file and run on http://localhost
The express code run on http://localhost:8080
I hope this may help you.
Thank for your answer. @dougwilson
It looks like your axios client is not sending the proper CORS headers to allow cookies to work.
@dumpsayamrat
I just solved the same problem.
use: vue+axios+express+cros
cros:
app.use(cors({
origin:['http://localhost:8080'],
methods:['GET','POST'],
credentials: true // enable set cookie
}));
axios: vue/main.js
axios.defaults.withCredentials = true // enable axios post cookie, default false
Most helpful comment
@dumpsayamrat
I just solved the same problem.
use: vue+axios+express+cros
cros:
axios: vue/main.js