将基于react-router
的webapp部署到在node.js
服务器下运行的生产是否可以?除非首先加载server.com/about
,否则部署静态文件会阻止index.html
之类的链接工作。人们可以通过使用HashRouter
来解决这个问题,但在这条路线上似乎是老派。
index.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import App from './js/App';
import About from './js/About';
import registerServiceWorker from './registerServiceWorker';
import './index.css';
import { BrowserRouter as Router, Route } from 'react-router-dom';
ReactDOM.render(
<Router>
<App>
<Route path='/about' component={About} />
</App>
</Router>
, document.getElementById('root'));
registerServiceWorker();
答案 0 :(得分:1)
你可以使用nginx回退任何路由(例如server.com/about)到index.html
例如
location ^~ / {
alias /usr/local/theapp/dist;
try_files $uri $uri/ /index.html;
access_log /var/log/nginx/theapp/acces.web.log;
error_log /var/log/nginx/theapp/error.web.log debug;
}
# assets
location ~ ^/.+\..+$ {
try_files $uri =404;
alias /usr/local/theapp/dist;
error_log /var/log/nginx/theapp/error.web.log debug;
}
答案 1 :(得分:0)
不是最漂亮的解决方案,但在nginx try_files $uri $uri/ /index.html;
旁边解决这样的问题可以解决问题。
class OnLoadHack extends Component {
componentDidMount() {
const { location, match, history } = this.props;
if(process.env.NODE_ENV !== 'development' && !match.isExact){
history.push(location.pathname + location.search)
}
}
render() {
return null
}
}
ReactDOM.render(
<Router>
<App>
<Route path='/' component={OnLoadHack} />
<Route path='/about' component={About} />
</App>
</Router>
, document.getElementById('root'));
registerServiceWorker();