我正在使用React-router,当我点击链接按钮时,它工作得很好,但当我刷新我的网页时,它没有加载我想要的东西。

例如,我在localhost/joblist和一切都很好,因为我到达这里按下一个链接。但如果我刷新网页,我会得到:

Cannot GET /joblist

默认情况下,它不是这样工作的。最初我有我的URL localhost/#/和localhost/#/joblist,他们工作得很好。但我不喜欢这种类型的URL,所以试图删除#,我写道:

Router.run(routes, Router.HistoryLocation, function (Handler) {
 React.render(<Handler/>, document.body);
});

这个问题不会发生在localhost/,这个总是返回我想要的。

这个应用程序是单页的,所以/joblist不需要向任何服务器询问任何事情。

我的整个路由器。

var routes = (
    <Route name="app" path="/" handler={App}>
        <Route name="joblist" path="/joblist" handler={JobList}/>
        <DefaultRoute handler={Dashboard}/>
        <NotFoundRoute handler={NotFound}/>
    </Route>
);

Router.run(routes, Router.HistoryLocation, function (Handler) {
  React.render(<Handler/>, document.body);
});

当前回答

如果你正在使用nginx托管,需要快速修复…

在你的nginx配置中添加以下代码:

location / {
  try_files $uri /index.html;
}

其他回答

这可以解决你的问题。

在生产模式下的React应用程序中,我也遇到了同样的问题。这里有两个解决这个问题的方法。

解决方案1。将路由历史更改为“hashHistory”,而不是browserHistory

<Router history={hashHistory} >
   <Route path="/home" component={Home} />
   <Route path="/aboutus" component={AboutUs} />
</Router>

现在使用命令构建应用程序

sudo npm run build

然后将构建文件夹放在var/www/文件夹中。现在,在每个URL中添加#标签,应用程序就可以正常工作了。就像

localhost/#/home
localhost/#/aboutus

解决方案2:没有#标签使用browserHistory,

在路由器中设置你的history = {browserHistory}。现在使用sudo npm run build构建它。

您需要创建“conf”文件来解决404 not found页面。conf文件应该是这样的。

打开终端,输入以下命令

cd /etc/apache2/sites-available
ls
nano sample.conf

在其中添加以下内容

<VirtualHost *:80>
    ServerAdmin admin@0.0.0.0
    ServerName 0.0.0.0
    ServerAlias 0.0.0.0
    DocumentRoot /var/www/html/

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
    <Directory "/var/www/html/">
            Options Indexes FollowSymLinks
            AllowOverride all
            Require all granted
    </Directory>
</VirtualHost>

现在您需要使用以下命令启用sample.conf文件:

cd /etc/apache2/sites-available
sudo a2ensite sample.conf

然后,它将要求您重新加载Apache服务器,使用

sudo service apache2 reload or restart

然后打开您的localhost/build文件夹,并添加包含以下内容的.htaccess文件。

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^.*$ / [L,QSA]

现在应用程序运行正常。

注意:0.0.0.0 IP地址修改为本地IP地址。

Preact路由器Preact解决方案

工作与刷新和直接访问

对于那些通过谷歌发现这一点的人,这里有一个preact-router +哈希历史的演示:

const { h, Component, render } = preact; /** @jsx h */
const { Router } = preactRouter;
const { createHashHistory } = History;
const App = () => (
    <div>
        <AddressBar />

        <Router history={createHashHistory()}>
            <div path="/">
                <p>
                    all paths in preact-router are still /normal/urls.
                    using hash history rewrites them to /#/hash/urls
                </p>
                Example: <a href="/page2">page 2</a>
            </div>
            <div path="/page2">
                <p>Page Two</p>
                <a href="/">back to home</a><br/>
            </div>
        </Router>
    </div>
);

斯菲德尔

产品堆栈:React, React Router v4, BrowswerRouter, Express.js, Nginx

User BrowserRouter for pretty URLs File app.js import { BrowserRouter as Router } from 'react-router-dom' const App = () { render() { return ( <Router> // Your routes here </Router> ) } } Add index.html to all unknown requests by using /* File server.js app.get('/*', function(req, res) { res.sendFile(path.join(__dirname, 'path/to/your/index.html'), function(err) { if (err) { res.status(500).send(err) } }) }) bundle Webpack with webpack -p run nodemon server.js or node server.js

你可能想让nginx在服务器块中处理这个问题,忽略第2步:

location / {
    try_files $uri /index.html;
}

我也遇到过同样的问题,这个解决方案对我们很有效……

背景:

我们在同一台服务器上托管多个应用程序。当我们刷新服务器时,它不知道该在目标文件夹的哪个位置查找特定应用程序的索引。上面的链接将把你带到我们的工作…

我们正在使用:

文件package.json:

"dependencies": {
  "babel-polyfill": "^6.23.0",
  "ejs": "^2.5.6",
  "express": "^4.15.2",
  "prop-types": "^15.5.6",
  "react": "^15.5.4",
  "react-dom": "^15.5.4",
  "react-redux": "^5.0.4",
  "react-router": "^3.0.2",
  "react-router-redux": "^4.0.8",
  "redux": "^3.6.0",
  "redux-persist": "^4.6.0",
  "redux-thunk": "^2.2.0",
  "webpack": "^2.4.1"
}

我的webpack.config.js文件:

/* eslint-disable */
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const babelPolyfill = require('babel-polyfill');
const HTMLWebpackPluginConfig = new HtmlWebpackPlugin({
  template: __dirname + '/app/views/index.html',
  filename: 'index.html',
  inject: 'body'
});

module.exports = {
  entry: [
    'babel-polyfill', './app/index.js'
  ],
  output: {
    path: __dirname + '/dist/your_app_name_here',
    filename: 'index_bundle.js'
  },
  module: {
    rules: [{
      test: /\.js$/,
      loader: 'babel-loader',
      query : {
          presets : ["env", "react", "stage-1"]
      },
      exclude: /node_modules/
    }]
  },
  plugins: [HTMLWebpackPluginConfig]
}

我的index.js文件

import React from 'react'
import ReactDOM from 'react-dom'
import Routes from './Routes'
import { Provider } from 'react-redux'
import { createHistory } from 'history'
import { useRouterHistory } from 'react-router'
import configureStore from './store/configureStore'
import { syncHistoryWithStore } from 'react-router-redux'
import { persistStore } from 'redux-persist'

const store = configureStore();

const browserHistory = useRouterHistory(createHistory) ({
  basename: '/your_app_name_here'
})
const history = syncHistoryWithStore(browserHistory, store)

persistStore(store, {blacklist: ['routing']}, () => {
  console.log('rehydration complete')
})
// persistStore(store).purge()

ReactDOM.render(
    <Provider store={store}>
      <div>
        <Routes history={history} />
      </div>
    </Provider>,
  document.getElementById('mount')
)

我的app.js文件:

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

app.use(express.static(__dirname + '/dist'));
// app.use(express.static(__dirname + '/app/assets'));
app.set('views', __dirname + '/dist/your_app_name_here');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

app.get('/*', function (req, res) {
    res.render('index');
});

app.listen(8081, function () {
  console.log('MD listening on port 8081!');
});

如果您在谷歌桶上运行它,简单的解决方案是考虑'index.html'为错误(404 not found)页面。

这样做:

在桶的列表中,找到您创建的桶。 单击桶关联的桶溢出菜单(…),选择“编辑网站配置”。 在网站配置对话框中,将主页也指定为错误页面。