首页 文章

React服务器端渲染如何处理RESTful API(react-router express)?

提问于
浏览
1

我有反应SSR的问题 . 我使用react-router作为我的app路由管理器 .

在服务器端,它可能看起来像这样(server.js):

var app = express();
app.get("*",function(req, res ){
     match({routes:AppRoutes, location:req.url},

      function(err, redirectLocation, renderProps){
        if (error) {
          res.send(500, error.message)
        } else if (redirectLocation) {
          res.redirect(302, redirectLocation.pathname + redirectLocation.search)
        } else if (renderProps) {
          res.send(200, renderToString(<RoutingContext {...renderProps} />))
        } else {
          res.send(404, 'Not found')
       }
    });
});

如果react-router消耗所有 GET 路由,如果我在服务器端需要RESTful API,我该如何将它与react-route分开?

如果我在前端有一个组件:

class Post extends Component{
    componentDidMount(){
       fetch('/api/post')
         .then(function(response){
              //change component state or do other
         })
         .catch(function(err){
             //handle error
         })
    } 
     render(){
      // 
     }
}

该组件如何通过RESTful API与服务器通信?
Express能提供这样的RESTful API结构吗?

app.get("/api/post",function(){
    //do something and response
});

我真的不明白 .

1 回答

  • 2

    问:“如果react-router消耗所有GET路由,如果我在服务器端需要RESTful API,我该如何将它与react-route分开?”

    答:您可以使用您编写的代码监听API调用:

    app.get("/api/post",function(){
        //do something and response
    });
    

    但是你必须把它放在你监听 "*" 的其他代码之上 .

    问:“这个组件如何通过RESTful API与服务器通信?”

    答:在服务器上呈现时,您的组件不会执行Ajax调用 . 服务器端不会调用函数 componentDidMount .

相关问题