Express session not saved from page to page
I am trying to save sessions, but when I make a session, there is no next request.
When I send an ajax request to /login
, I establish a session with req.session.username
and then send back the object that says {success:true}
. Then I refresh the page, and if the username exists in the session, I show the user page, otherwise I show the master page.
Every time I refresh the page in /
, it always shows the login even after submitting a request to /login
and establishing a session. Why is the session not being saved?
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 an Ajax request, I return the following header:
set-cookie:connect.sid=s%3At25S_TmjwL6vVkhyJ9LuKIyy4EH1LTcy.Zu4fBpMibfjmMofxQI5K%2FmgAYHWFqQf3x8HPzcQbDH4; Path=/; Expires=Sun, 23 Jul 2017 15:29:26 GMT; HttpOnly
Edit
So, after commenting out everything in my code and slowly splitting and testing the lines, I found that this doesn't work:
req.session.username = req.body.username // body.username Contains a string
However, this works:
req.session.username = 'Billy'
I'm not sure why he does this. Any suggestions?
source to share
So I figured out my problem, it had nothing to do with the server, but with the ajax request fetch()
.
I needed to add an option to it credentials: 'include'
like this:
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()
})
source to share