对/auth
的客户端POST请求:
async loginUser({commit}, payload) {
await fetch('http://localhost:4000/auth', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
})
}
有效载荷:
{
username: 'admin@example.com',
password: 'xyz'
}
后端index.js
以通常的方式开始:
const express = require('express')
const app = express()
const cors = require('cors')
const bodyParser = require('body-parser')
const port = 4000
/// middleware
app.use(cors())
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
护照的基本设置:
const passport = require('passport')
const LocalStrategy = require('passport-local').Strategy
app.use(passport.initialize());
app.use(passport.session());
我希望在发布到/auth
路线时采用本地策略:
passport.use(new LocalStrategy({
usernameField: 'username',
passwordField: 'password'
}, function (username, password, done) {
console.log("Verification function called"); // not hit
return done(null, username);
}
));
passport.serializeUser(function (user, done) {
done(null, user);
});
passport.deserializeUser(function (user, done) {
done(err, user);
});
app.use(passport.initialize());
app.use(passport.session());
现在在路线中:
// routes
app.get('/', (req, res) => {res.json({info: 'APP Running' })})
app.listen(port, () => { console.log(`App running on port ${port}.`) })
app.post('/auth', function (req, res, next) {
passport.authenticate('local', function (error, user, info) {
console.log(`error: ${error}`);
console.log(`user: ${user}`);
console.log(info);
if (error) {
res.status(401).send(error);
} else if (!user) {
res.status(401).send(info);
} else {
next();
}
res.status(401).send(info);
})(req, res);
},
// function to call once successfully authenticated
function (req, res) {
res.status(200).send('logged in!');
});
我的问题是,策略功能永远不会被点击,因此我无法为用户查询数据库。
console.log(
错误:$ {error} );
返回null
console.log(
用户:$ {user} );
返回false
console.log(info);
返回{ message: 'Missing credentials' }
我在这里真的缺少明显的东西吗?