javascript - 我可以使用 react-router 为 github-pages 站点创建路由吗?

标签 javascript react-router url-routing single-page-application github-pages

好的,所以我使用 React 和 React-Router 制作了一个 SPA,并将其推送到 github 页面,但是当我在浏览器中刷新或单击返回时,我编写的所有路由都不起作用。我在本地提供页面时遇到了同样的问题,但随后转到 this SO answer并制作了一个 server.js 文件,该文件在每条路线上都提供了对我的静态 HTML 页面的重定向。这是文件的样子:

"use strict";
let express = require('express');
let path = require('path');


let app = express();

app.use(express.static('public'));

app.get('/contact', function(req, res){
  res.sendFile('public/index.html', { root: __dirname });
})

app.get('/about', function(req, res){
  res.sendFile('public/index.html', { root: __dirname });
})

app.get('*', function(req, res){
  res.sendFile('public/index.html', { root: __dirname });
})

app.listen(8080, function(){
  console.log('Listening on port 8080!')
})

现在,我的问题是,当我将项目推送到 github 页面时,所有这些逻辑都被忽略了,github 的路由接管了,我遇到了同样的问题,无法刷新或直接转到 /contact。或 /about .我知道这似乎是一个明显的问题,因为 github 页面旨在仅托管静态站点,但我看到有人暗示为每个路由创建静态页面的其他方法,例如 this reddit post 中的答案,但我不知道该怎么做。

我还应该提一下,因为我已经在 user-name.github.io 有一个站点。 , 所以这个网站被托管在 user-name.github.io/projects ,让我的/路线。我不知道这是否有什么不同,我只是想我应该提一下。

我想我已经用尽了所有的方法来尝试在 gh-pages 上成功地托管它,我知道有像 Single Page Apps for GitHub Pages 这样的项目。尝试解决这个问题,但是,我只是想看看有没有人在求助之前有幸做到这一点。

仅供引用,这是我的 app.js (包含路由逻辑):
import React, {Component} from 'react';
import {render} from 'react-dom';
import {Router, Route, browserHistory, IndexRoute} from 'react-router';
//Import custom components
import About from '../components/about.js';
import Contact from '../components/contact.js';
import Sidebar from '../components/sidebar.js';
import Imagelist from '../components/image-list.js';


  render(
      <Router history={browserHistory}>
        <Route path="/" component={Sidebar}>
          <IndexRoute component={Imagelist}/>
          <Route path="/about" component={About}/>
          <Route path="/contact" component={Contact}/>
        </Route>
      </Router>,
      document.getElementById('content')
    );

对此的任何帮助将不胜感激,如果有帮助,我们很乐意包含更多代码。

最佳答案

我认为您需要将 browserHistory 更改为 hashHistory .. 这样您就可以将其与 gh 一起使用...它将路径从/home 更改为 #/home

关于javascript - 我可以使用 react-router 为 github-pages 站点创建路由吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40776651/

相关文章:

javascript - jPlayer 和 Summernote 不能很好地协同工作

javascript - 除了一条路由之外,所有路由都使用基本名称子目录吗?

javascript - 链接到 Vue.js 中 vuex 存储中引用的图像

php - 覆盖默认路由但在必要时调用它

javascript - 如何在 &lt;input&gt; 为空时发出 CSS 警告(最好没有 JS)

javascript - 实时代码示例 : cytoscape. js 初始化——不完整?

javascript - 动态 JQuery 对象选择器

javascript - react route 的大写情况

css - React-router 在刷新时不为嵌套页面加载 css

php - URL 路由器中的组和中间件