[英]Express app not rendering my react components
I'm building a Express app using React. 我正在使用React构建Express应用。 I start my server, go to localhost and I see a blank page, when I check the developer tools on chrome it shows me that my js file is plain HTML.
我启动服务器,进入本地主机,然后看到一个空白页,当我在chrome上检查开发人员工具时,它显示出我的js文件是纯HTML。 Why is that?
这是为什么?
This is my server.js
: 这是我的
server.js
:
var express = require('express');
var app = express();
var port = process.env.NODE_ENV || 3000;
app.get('*', function(req, res) {
res.sendFile(__dirname + '/public/views/index.html');
});
app.listen(port, function() {
console.log('Listening to http://localhost:' + port);
});
This is my app.js
: 这是我的
app.js
:
var React = require('react'),
ReactDOM = require('react-dom');
var App = React.createClass({displayName: "App",
render () {
return (
React.createElement("h1", null, "Hello World!!!!!")
)
}
});
ReactDOM.render(React.createElement(App, null), document.getElementById('main-app'));
My index.html
: 我的
index.html
:
<body>
<div id="main-app"></div>
</body>
<script src="public/assets/dist/javascripts/app.js"></script>
This is what I see on developer tools: image 这是我在开发人员工具上看到的: 图像
The problem is that whatever file you are requesting to your server you are always returning index.html
. 问题在于,无论您要向服务器请求的文件是什么,总是返回
index.html
。
So when you go to http://localhost:3000/ you get index.html
因此,当您访问http:// localhost:3000 /时,您将获得
index.html
The problem is that your index.html
then requests public/assets/dist/javascripts/app.js
but you still return index.html
as if it was app.js
. 问题是您的
index.html
然后请求public/assets/dist/javascripts/app.js
但是您仍然返回index.html
,就像它是app.js
。
You need to update your route so it returns the file that was requested. 您需要更新路由,以便它返回所请求的文件。
I think adding this to your server.js
might fix it. 我认为将此添加到您的
server.js
可能会解决它。
app.use(express.static(__dirname + '/public'));
Instead of 代替
app.get('*', function(req, res) {
res.sendFile(__dirname + '/public/views/index.html');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.