我正在使用React构建Express应用程序。我启动我的服务器,转到localhost,我看到一个空白页面,当我检查chrome上的开发人员工具时,它向我显示我的js文件是纯HTML。那是为什么?
这是我的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);
});
这是我的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'));
我的index.html
:
<body>
<div id="main-app"></div>
</body>
<script src="public/assets/dist/javascripts/app.js"></script>
这是我在开发人员工具上看到的: image
答案 0 :(得分:2)
问题在于,无论您向服务器请求的是哪个文件,都要始终返回index.html
。
因此,当您转到http://localhost:3000/时,您会获得index.html
问题是,您的index.html
会请求 public/assets/dist/javascripts/app.js
,但您仍然会将index.html
作为app.js
返回。
您需要更新路线,以便返回所请求的文件。
我认为将此添加到您的server.js
可能会解决此问题。
app.use(express.static(__dirname + '/public'));
而不是
app.get('*', function(req, res) {
res.sendFile(__dirname + '/public/views/index.html');
});