我如何从快递服务器传递数据来反应意见?

我有一个简单的快速服务器连接到一个orientdb数据库。 我需要从快递中传递信息来反应意见。 例如,在expression我有:

router.get('/', function(req, res, next) { Vertex.getFromClass('Post').then( function (posts) { res.render('index', { title: 'express' }); } ); }); 

所以,在这个例子中,我需要在我的反应索引组件中, postsvariables设置组件的状态。 (我只在前端使用反应,而不是在服务器端)

 class IndexPage extends React.Component { constructor(props) { super(props); this.state = { posts: [] }; } render() { return ( <div> <Posts posts={posts} /> </div> ); } } 

我如何从快递中得到回复?

我发现也许我可以从反应做一个Ajax请求,但我认为这不是最好的方法。

如果我需要以实时的方式获取post,例如使用socket.io,有什么区别?

PD:在expression我有可能使用一些模板引擎像把手或霍根。 这个模板引擎可以帮助这个主题吗?

谢谢!!!

我认为你最好的select是确实从客户端做出某种networking请求。 如果你的目标是保持简单的应用程序,并不想要一个国家pipe理图书馆(如Redux),你可以做类似的事情

 class IndexPage extends React.Component { constructor(props) { super(props); this.state = { posts: [] }; } componentDidMount() { fetch('/') // or whatever URL you want .then((response) => response.json()) .then((posts) => this.setState({ posts: posts, }); } render() { return ( <div> <Posts posts={this.state.posts} /> </div> ); } } 

在你的response ,应该有一个JSON表示的post集合。

还要注意render方法和访问posts

有关Fetch API的更多信息,请参阅MDN (请注意,您需要为旧版浏览器填充polyfill)。

编辑:对于socket.io我将它的实例存储在某处,并将其作为道具传递给组件。 那么你可以做一些类似的事情

 class IndexPage extends React.Component { ... componentDidMount() { this.props.socket.on('postReceived', this.handleNewPost); } handleNewPost = (post) => { this.setState({ posts: [ ...this.state.posts, post, ], }); } ... } 

服务器端的部分是相似的,例如见Socket.io聊天的例子 。