Reputation: 36351
I am trying to save sessions, but when I do the session doesn't exist on the next request.
When I send an ajax request to /login
I set the session with req.session.username
and then I send back an object that says {success:true}
. I then refresh the page, and if the username exists on the session I display the user page otherwise I display the main page.
Everytime I refresh the page at /
It always shows the login even after I send the request to /login
and set the session. Why is the session not saving?
let express = require('express')
let sessions = require('express-session')
let bodyParser = require('body-parser')
let app = express()
app.use(sessions({
secret: 'connection-id',
resave: true,
saveUninitialized: true,
cookie: { maxAge: 60000 }
}))
app.use(bodyParser.json())
app.get('/', (req, res) => {
if (req.session.username) {
res.render('pages/home')
} else {
res.render('pages/index')
}
}).post('/login', (req, res) => {
if (req.xhr) {
req.session.username = req.body.username
res.send({ success: true })
} else {
res.sendStatus(500)
}
})
Client Side:
let response = await fetch('/login', {
method: 'post',
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: new FormData((document.getElementById('login-form'))).toJson()
})
let json = await response.json()
if (json.success) {
window.location.href = '/'
}
When I make the Ajax Request, I get the following header back:
set-cookie:connect.sid=s%3At25S_TmjwL6vVkhyJ9LuKIyy4EH1LTcy.Zu4fBpMibfjmMofxQI5K%2FmgAYHWFqQf3x8HPzcQbDH4; Path=/; Expires=Sun, 23 Jul 2017 15:29:26 GMT; HttpOnly
So after commenting everything out in my code and slowly uncommenting and testing the lines, I found that this does not work:
req.session.username = req.body.username // body.username Contains a string
However, this does work:
req.session.username = 'Billy'
I am not sure why it is doing this. Any suggestions?
Upvotes: 3
Views: 792
Reputation: 36351
So I figured out my issue, it had nothing to do with the server but the ajax fetch()
request.
I needed to add the option credentials: 'include'
to it like so:
let response = await fetch('/login', {
method: 'post',
credentials: 'include',
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: new FormData(document.getElementById('login-form')).toJson()
})
Upvotes: 3