后端 API w/ React Router

Backend API w/ React Router

我目前有一个 Express 后端,它为用户提供登录页面,它是 React 应用程序的一部分。应用程序页面上有一个按钮,可通过 Google 的 O-Auth 流程引导用户,最终返回用户信息,如下所示:

router.get("/google/redirect", passport.authenticate('google'), (req,res) => { // Returns user information from google...
    res.redirect("/dashboard");
    // req.user <–– My user information is here...
});

在我的应用程序的主要 server.js 文件中,我有一个 app.get 路由在中间件下方等待我的身份验证,准备好提供我的 React.js 编译索引,这里:

app.get('*', (req, res) => {
    res.sendFile(path.join(publicPath, "index.html"));
});

GET 路由服务于我的 React.js 文件,其中包含基于我的 Redux 状态的 "public" 和 "private" 路由。 React 文件(在编译到我的索引之前。html/javascript 由上述路由提供的包)在编译之前看起来像这样:

const store = configureStore();
const jsx = (
  <Provider store={store}>
    <AppRouter />
  </Provider>
);
const renderApp = () => {
    ReactDOM.render(jsx, document.getElementById('app'));
    hasRendered = true;
};

renderApp();

我希望能够以某种方式'send' 将数据从我的 Express 后端发送到我的 Redux 状态。这样,当用户登录时,Redux "isAuthenticated" 状态发生变化,然后当我被路由到私有“/dashboard”路由时。

如何将此 MongoDB 数据发送到我的 Redux 存储,然后将用户重新路由到适当的页面 (\dashboard)?或者有没有更好的方法来呈现初始 React 状态,以便我可以显示登录屏幕,然后一旦用户登录,重定向他们并根据来自后端的信息更改 Redux 状态?

我看到你的主要问题是如何从 MongoDB 检索数据到 React,然后更改状态。

它将像来自客户端 --> 服务器的任何其他请求一样完成。

现在如何从 Mongodb 请求数据取决于它的实现:

如果您 运行 MongoDb 作为节点包,例如 Mongoose,那么您可以从 React --> Express Server 进行调用,它将提供数据库中的数据。

来自 React --> Express 的请求将如下所示:

反应代码:

 callAPI(){
    fetch("http://localhost:9000/testAPI")
      .then(res=>res.text())
      .then(res=> this.setState({apiResponse :res}))
      .catch(err=> err);
  }

 componentDidMount(){
    //this can be any event. This is just an example
    this.callAPI();
  }

然后 Express 必须使用您要查找的数据来服务器路由 /testAPI。

快递testAPI.js

express = require('express');

router = express.Router();

router.get('/', function(req,res, next) {
    res.send('API is working perfectly.');
});

module.exports = router;

如果这回答了您的问题,请告诉我。