After running the axios post method, it gives an error no matter how I go to the '/api/user' path, if I try to run the getUser function after running the onSubmitLogin function, it still gives an error.
I am attaching all relevant codes
User login post method axios
function onSubmitLogin(data) {
var url = "http://localhost:3001/api/user/login";
axios({
method: "POST",
data: {
username:data.username,
password:data.password
},
withCredentials: true,
url: url
}).then(response => console.log(response))
}
User login post method nodejs
exports.userLogin = (req, res, next) => {
passport.authenticate('local', (err, user, info) => {
if (err) throw err;
if (!user) {
res.status(404).send('user not found')
}
else {
req.login(user, err => {
if (err) throw err;
res.status(200).send(req.user)
})
}
})(req,res,next)
}
getUser function axios
function getUser() {
var getUrl = "http://localhost:3001/api/user"
axios({
method:"GET",
withCredentials:true,
url:getUrl,
}).then(response => console.log(response.data))
}
user get method nodejs
exports.getUser = (req,res) => {
res.send(req.user)
}
and passport-config.js
const LocalStrategy = require('passport-local').Strategy
const bcrypt = require('bcrypt');
const User = require('./models/userModel.js');
function initialize(passport) {
passport.use(
new LocalStrategy((username, password, done) => {
User.findOne({ username: username })
.then((user, err) => {
if (err) throw err;
if (!user) return done(null, false);
bcrypt.compare(password, user.password, (err, result) => {
if (err) throw err;
if (result) {
return done(null, user)
} else {
return done(null, false)
}
})
})
})
);
passport.serializeUser((user, cb) => {
cb(null, user.id)
});
passport.deserializeUser((id, cb) => {
User.findOne({ _id: id })
.then((err, user) => {
cb(err, user)
})
})
}
module.exports = initialize;
I don't get this error when I set the withCredentials value to false, but at that time the authentication system does not work properly.