如何将ReactJS与expressJS集成

时间:2016-08-31 07:54:32

标签: node.js express reactjs

首先,我在ReactJS中非常新。我已根据以下链接完成了简单的reactjs项目。 http://www.tutorialspoint.com/reactjs/reactjs_environment_setup.htm我可以通过运行" npm start"来完美地运行和测试。但是,当我尝试与expressJs集成编辑/开发如下编码时,我根本无法渲染。

的package.json

  "scripts": {
    "start": "node server.js"
  }

server.js

var express = require('express');
var path = require('path');

var app = express();

var isProduction = process.env.NODE_ENV === 'production';
var port = isProduction ? process.env.PORT : 3000;
var publicPath = path.resolve(__dirname, '/');

// We point to our static assets
app.use(express.static(publicPath));
console.log(publicPath)

// And run the server
app.listen(port, function () {
  console.log('Server running on port ' + port);
});

每当我渲染为" npm start"时,请遇到以下情况。

  

无法获取/

2 个答案:

答案 0 :(得分:1)

使用快递js创建一个api,为您提供index.html页面

app.get("/", function(req, res){
    res.sendFile(dirname + "index.html");
})

在这种情况下,您将能够呈现页面。

答案 1 :(得分:0)

@Shubham Khatri提到的是对的,但会有一个问题。如果您的React应用程序中定义了任何路由,即http://appDomain.com/productshttp://appDomain.com/bloghttp://appDomain.com/articles将无效。

原因是,您没有在Express应用程序中为那些定义任何路由处理程序(就像您为root /所做的那样)

如果您愿意使用Express作为后端服务器运行React应用程序,则可能需要在单独的端口上运行Express应用程序,即 7070

您的React应用程序可以在单独的端口上单独运行,即 8080 。 React应用程序可以进一步与Express定义的Routes,Urls作为API端点进行通信以获取数据。

如需进一步详情/讨论,请参阅此帖: ReactJS, ExpressJS different application Architectures & Modeling and Deployments