Hib*_*ber 3 javascript router static-files node.js reactjs
我是新来的反应者,我正在尝试用它构建一个聊天应用程序。我使用了react-router来根据URL加载不同的组件。在我的React项目文件(client / src / index.js)中,代码如下:
import {BrowserRouter as Router, Route} from 'react-router-dom';
...
ReactDOM.render(
<Router>
<div>
<Route exact path='/' component={App} />
<Route path='/customer' component={CustomerPage} />
<Route path='/support/:support_id' component={SupportPage} />
</div>
</Router>,
document.getElementById('root')
);
...
Run Code Online (Sandbox Code Playgroud)
当我使用“ npm start”在react文件夹中启动它时,它可以找到。但是,当我运行“ npm run build”并通过express服务器提供静态文件时,它只能在“ /”路径中提供应用页面,而对于“ / customer”和“ / support /:support_id”路径,它将加载没有。
在快速服务器文件夹中,我通过以下方式加载静态文件:
服务器/ app.js:
...
var indexRouter = require('./routes/index');
app.use('/static', express.static(path.join(__dirname, '../client/build//static')));
app.use('/', indexRouter);
...
Run Code Online (Sandbox Code Playgroud)
服务器/路由/index.js:
...
router.get('/', function(req, res) {
res.sendFile('index.html', {root: path.join(__dirname, '../../client/build/')});
});
...
Run Code Online (Sandbox Code Playgroud)
任何帮助将不胜感激!
React Router在浏览器中执行所有路由,因此您需要确保将index.html每个路由的文件都发送给用户。
这应该是您所需要的:
app.use('/static', express.static(path.join(__dirname, '../client/build//static')));
app.get('*', function(req, res) {
res.sendFile('index.html', {root: path.join(__dirname, '../../client/build/')});
});
Run Code Online (Sandbox Code Playgroud)