在MERN Stack上进行项目时遇到问题

时间:2018-10-09 10:27:00

标签: javascript reactjs express oauth cors

在MERN Stack上进行项目时遇到问题。

我的React应用程序在端口3000上运行,并且在5000上运行了api。我遇到的是,在使用redux添加0auth功能的同时,我收到类似“跨域请求被阻止:相同的源策略禁止读取远程资源的错误” here。(原因:CORS标头“ Access-Control-Allow-Origin”缺失)。”

现在我的逻辑结构就像:

我已经为护照定义了Google策略。快速路由(http://localhost:5000/api/user/auth/google)和回调URL(http://localhost:5000/api/user/auth/google/callback)中的已定义路由。现在,当我直接访问“ http://localhost:5000/api/user/auth/google”时,我可以完成过程,但是当我从react app的reducers调用它时,我遇到了上面提到的错误。

我的代码如下:

// 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
        })
      }
    )
}       

1 个答案:

答案 0 :(得分:0)

通过使用Express中间件来允许CORS。使用npm install cors安装CORS。导入CORS import cors from 'cors'。如果您的Express-instance称为 app ,请与app.use(cors())一起使用中间件。

示例:

import express from 'express';
import cors from 'cors';

const app = express();
app.use(cors());

让我知道它是否可以解决问题