Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
134 views
in Technique[技术] by (71.8m points)

node.js - 'Access-Control-Allow-Origin' header problems with login

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are missing set it should be setHeader instead header

res.setHeader("Access-Control-Allow-Credentials", true);
res.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Authorization, Origin, X-Requested-With, Content-Type, Accept');

EDIT 1

for production can you allow it to all by setting as:

res.setHeader('Access-Control-Allow-Origin', '*');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...