Доброе утро.Скажите пожалуйста,почему при отправке формы мне пишет cannot get /login,а при перезагрузке этого /login проходит мой обработчик запроса?
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>
NODE.JS:
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}!`));