简体   繁体   中英

I encountered a problem while working on my project on MERN Stack

I encountered a problem while working on my project on MERN Stack.

My React app is running on port 3000 and express api on 5000. What I encountered is, while adding 0auth functionality using redux, I am getting error like "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource here . (Reason: CORS header 'Access-Control-Allow-Origin' missing)."

Now the structure of my logic is like :

I have defined google strategy for passport. Defined routes in express route ( http://localhost:5000/api/user/auth/google ) and callback url ( http://localhost:5000/api/user/auth/google/callback ). Now when I am directly accessing " http://localhost:5000/api/user/auth/google ", I am able to complete process, but when I am calling it through reducers from react app, I am getting above mentioned error.

My code is the following:

// Routes
router.get(
  "/auth/google",
  passport.authenticate("google", {
    scope: ["profile", "email"]
  })

);
router.get(
  "/auth/google/callback",
  passport.authenticate("google", {
    failureRedirect: "/",
    session: false
  }),
  function(req, res) {
    var token = req.user.token;
    console.log(res);
    res.json({
      success: true,
      token: 'Bearer ' + token,
    });
  }
);


//Reducers Action

export const googleLoginUser = () => dispatch => {
  axios
    .get('api/users/auth/google')
    .then((res) => {
      //save to local Storage
      const {
        token
      } = res.data;
      // Set token to local storage
      localStorage.setItem('jwtToken', token);
      //set token to auth header
      setAuthToken(token);
      // Decode token to get user data
      const decoded = jwt_decode(token);
      console.log(decoded);
      // set current user
      dispatch(setCurrentUser(decoded));
    })
    .catch(err => {
        console.log(err);
        dispatch({
          type: GET_ERRORS,
          payload: err.response.data
        })
      }
    )
}       

Allow CORS by using middleware for Express. Install CORS with npm install cors . Import CORS import cors from 'cors' . Use middleware with app.use(cors()) if your Express-instance is called app .

Example:

 import express from 'express'; import cors from 'cors'; const app = express(); app.use(cors()); 

Let me know if it solves the problem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM