问题
im using passport js express, when i login and get req.user on postman it works as i expect. But when i try on web browsers(im doing get request with axios) its doesnt work. The problem is passport.deserialize doesnt work on axios get.
i tried different http get request methods (fetch, jquery.get, axios) its not about that. Also when i do manuel request to my server it turns as expected. I have different project, code is nearly same and works on that. I cant understand what is the problem.
app.use(
session({
secret: 'fraggle-rock', //pick a random string to make the hash that is generated secure
store: new MongoStore({ mongooseConnection: db }),
resave: false, //required
saveUninitialized: false, //required
})
);
app.use(passport.initialize());
app.use(passport.session());
passport.use(
new LocalStrategy(
{
usernameField: 'username', // not necessary, DEFAULT
},
function(username, password, done) {
User.findOne({ username: username }, (err, user) => {
if (err) {
return done(err);
}
if (!user) {
return done(null, false, { message: 'Incorrect username' });
}
if (!user.checkPassword(password)) {
return done(null, false, { message: 'Incorrect password' });
}
return done(null, user);
});
}
)
);
app.post('/login', passport.authenticate('local'), (req, res) => {
console.log('logged in', req.user);
var userInfo = {
username: req.user.username,
};
res.send(userInfo);
});
app.get('/user', (req, res, next) => {
console.log('===== userss!s!======');
console.log(req.user);
res.send(req.user);
/* if (req.user) {
res.json({ user: req.user });
} else {
res.json({ user: null });
}*/
});
PASSPORT SERIALIZE AND DESERIALIZE
const passport = require('passport');
const User = require('../database/models/user');
// called on login, saves the id to session req.session.passport.user = {id:'..'}
passport.serializeUser((user, done) => {
if (!user) {
console.log('no user');
} else {
console.log('*** serializeUser called, user: ');
console.log(user); // the whole raw user object!
console.log('---------');
done(null, { _id: user._id });
}
});
// user object attaches to the request as req.user
passport.deserializeUser((id, done) => {
console.log('------------------DeserializeUser called');
User.findOne({ _id: id }, 'username', (err, user) => {
if (err) {
console.log(err);
} else {
console.log('*** Deserialize user, user:');
console.log(user);
console.log('--------------');
done(null, user);
}
});
});
AXIOS
axios.get('http://localhost:8000/user')
.then(function(response) {
console.log(response);
})
.catch(function(error) {
console.log(error);
})
-------------------------------------------------------------------------
I SOLVED THIS, THE SOLUTION ON THE ANSWER
回答1:
I SOLVED THIS, THE SOLUTION IS SIMPLE... I WAS TRYING SINCE YESTERDAY.
HERE IS THE SOLUTION
Working on sending {withCredentials:true} parameter along with every request from the frontend so that the frontend sends cookie along with every request.
Added the following code in the backend:
app.use(cors());
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "frontendURL");
res.header("Access-Control-Allow-Credentials", true);
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});
Example front-end request for login handle:
const login_axios = axios.create({
withCredentials: true,
headers: {
Accept: "application/json",
"Content-Type": "x-www-form-urlencoded"
},
params: {
username: this.state.username,
password: this.state.password
}
});
login_axios
.post()
.then(function(response) {
console.log("RESPONSE");
console.log(response);
})
.catch(function(error) {
console.log("ERROR");
console.log(error);
});
来源:https://stackoverflow.com/questions/55996257/on-postman-get-session-returns-as-expected-on-chrome-not