React服务器端渲染如何与RESTFUL API(React-Router Express)相关



我对React SSR有问题。我将React-Router用作我的应用路线经理。

在服务器端,看起来像这样(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可以提供如此静止的API结构吗?

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

我真的不明白。

q:"如果react-router会消耗所有路线,如果我需要在服务器端静止的API,我该如何将其与React-Route分开?"

a:您可以使用您编写的代码收听API呼叫:

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

,但是您必须将其放在倾听"*"的其他代码之上。

Q:"此组件如何通过RESTFUL API与服务器通信?"

a:在服务器上渲染时,您的组件不会进行AJAX调用。函数componentDidMount不会在服务器端调用。

最新更新