首页 > 解决方案 > 我在 MERN Stack 上处理我的项目时遇到了问题

问题描述

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

我的 React 应用程序在端口 3000 上运行,并在 5000 上运行 api。我遇到的是,在使用 redux 添加 0auth 功能时,我收到类似“Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource 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 应用程序中的减速器调用它时,我遇到了上述错误。

我的代码如下:

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

标签: javascriptreactjsexpressoauthcors

解决方案


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

例子:

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

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

让我知道它是否解决了问题


推荐阅读