【问题标题】:I encountered a problem while working on my project on MERN Stack我在 MERN Stack 上处理我的项目时遇到了问题
【发布时间】:2019-03-14 02:24:17
【问题描述】:

我在 MERN Stack 上处理我的项目时遇到了问题。

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

现在我的逻辑结构是这样的:

我已经为护照定义了谷歌策略。在快速路由 (http://localhost:5000/api/user/auth/google) 和回调 url (http://localhost:5000/api/user/auth/google/callback) 中定义路由。现在,当我直接访问“http://localhost:5000/api/user/auth/google”时,我可以完成流程,但是当我通过 react 应用程序中的 reducer 调用它时,我遇到了上述错误。

我的代码如下:

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

【问题讨论】:

    标签: javascript reactjs express oauth cors


    【解决方案1】:

    通过使用 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());

    如果它解决了问题,请告诉我

    【讨论】:

      猜你喜欢
      • 2021-01-15
      • 1970-01-01
      • 2020-11-08
      • 1970-01-01
      • 2019-05-05
      • 1970-01-01
      • 2021-02-15
      • 1970-01-01
      • 2022-10-18
      相关资源
      最近更新 更多