It's my third day struggling with this issue.
I am getting this error:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 502. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled
However, I have no such problem when performing get request from the same server. I intentionally was breaking cors / headers setting to now allow the front end to access the api and found out the problem is with login. I tried performing post request for login with my own api and with axios, however I failed both times. At this point I dont know where to look for the issue. My app.js api file looks like this:
app.use(function (req, res, next) {
var allowedOrigins = ['http://localhost:3000', 'front end'];
var origin = req.headers.origin;
if (allowedOrigins.indexOf(origin) > -1) {
res.setHeader('Access-Control-Allow-Origin', origin);
}
res.header("Access-Control-Allow-Credentials", true);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Authorization, Origin, X-Requested-With, Content-Type, Accept');
next();
});
On front logging in looks like this:
export const handleLogin = (email, password) => {
return function (dispatch) {
let params = { email, password };
Api.post('/auth', params).then((res) => {
//dispatch(fetchUser2());
if(res.user){
dispatch({
type: FETCH_USER,
payload: res.user
})
}
});
}
}
But maybe issue somehow lies in passport, so Im also pasting the passport file:
module.exports = (passport) => {
passport.serializeUser((user, done) => {
done(null, user.id);
});
passport.deserializeUser((id, done) => {
Employee.findById(id).then((user) => {
done(null, user);
});
});
//passport strategies
passport.use('local', new LocalStrategy({
usernameField: 'email',
passwordField: 'password',
passReqToCallback: true,
},
function (req, email, password, done) {
Employee.findOne({ email: email }, function (err, user) {
if (err) { return done(err); }
if (!user) {
return done(null, false, { message: 'Incorrect username.' });
}
if (password != user.password) {
return done(null, false, { message: 'Incorrect password.' });
}
return done(null, user);
}).catch(errors => {
return done(errors, null);
})
}
));
}
and finally a route for auth in api:
app.post('/auth', function (req, res, next) {
passport.authenticate('local', function (err, user, info) {
if (err) {
return next(err);
}
if (!user) {
return res.status(401).send({
success: false,
msg: 'User not found'
});
}
req.logIn(user, function (err) {
if (err) {
return next(err);
}
res.status(200).send({
user: user,
msg: 'You're logged in'
});
return;
});
})(req, res, next);
});
After trying dummy post and get requests im almost certainly sure its passport's fault, because other post requests work
See Question&Answers more detail:
os