Answer the question
In order to leave comments, you need to log in
Why is the POST request not being processed?
Good morning. Can you please tell me why when I submit the form it says cannot get /login, but when I reload this /login my request handler goes through?
HTML/JS:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sessions auth</title>
</head>
<body>
<form method="POST" action="/login">
<input type="email" name="email">
<input type="password" name="password">
<input type="submit" value="Submit" onclick="send()">
</form>
<script type="text/javascript">
function send() {
var xhr = new XMLHttpRequest();
var body = 'email=' + encodeURIComponent(email) +
'&password=' + encodeURIComponent(password);
xhr.open("POST", '/login', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
// xhr.onreadystatechange = ...;
xhr.send(body);
}
</script>
</body>
</html>
const express = require('express');
const session = require('express-session');
const FileStore = require('session-file-store')(session);
const passport = require('passport');
const app = express();
const port = 3000;
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(
session({
secret: "secret",
store: new FileStore(),
cookie: {
path: "/",
httpOnly: true,
maxAge: 60 * 60 * 1000
},
resave: false,
saveUnitialized: false
})
);
require('./config');
app.use(passport.initialize());
app.use(passport.session());
app.get('/', (req, res) => res.sendFile(__dirname + '/index.html'));
app.get('/login', function(req, res, next) {
passport.authenticate('local', function(err, user) {
if (err) {
return next(err);
}
if (!user) {
return res.redirect('/');
}
req.logIn(user, function(err) {
if (err) {
return next(err);
}
return res.redirect('/admin');
});
})(req, res, next);
});
const auth = (req,res,next) => {
if(req.isAuthenticated()) {
next()
} else {
return res.redirect('/');
}
}
app.get('/admin', auth, (req, res) => {
res.send('Admin page')
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question