【问题标题】:React Router with Express, subpages are not routing correctly in production使用 Express 反应路由器,子页面在生产中没有正确路由
【发布时间】:2021-01-22 21:52:27
【问题描述】:

我有一个使用 React 路由器构建的 React 应用程序,并且托管在 Heroku 上。我可以很好地导航到主页('/')到其他页面('/about'),但如果我尝试从浏览器直接导航到子页面(例如'/about'),Express 会返回 500 错误。

无论请求如何,我都尝试始终返回 index.html 页面,然后让 React Router 处理路由,但有些事情实现不正确。这仅发生在 Heroku 上的 production 中;我的本地开发环境路由工作正常。

非根页面上的图像也会损坏。

文件结构:

build
..static
....css
....js
....media
node_modules
public
server
..server.js
src
..config
....switch.js
..imgs
..pages
..scss
..App.js
..index.js
package.json
Procfile
README.md
static.json

server.js:

const path = require('path');
const sslRedirect = require('heroku-ssl-redirect').default;
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;

app.use(sslRedirect());

if (process.env.NODE_ENV === 'production') {
    app.use(express.static('build'));
  app.get('*', (req, res) => {
        res.sendFile('index.html');
  });
} else {
  const publicPath = path.join(__dirname, '..', 'public');app.use(express.static(publicPath));app.listen(port, () => {
    console.log(`Server is up on port ${port}!`);
  });
  app.get('*', (req, res) => {
    res.sendFile(path.join(publicPath, 'index.html'));
  });
}

app.listen(port, () => {
  console.log('Server is up!');
});

App.js:

import React from 'react'
import Header from './header'
import Footer from './footer'
import Switch from './config/switch'
import styled from 'styled-components'

import './App.scss'

const App = styled.div`
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 100vh;
`

const AppContent = styled.div`
  width: 1200px;
  margin: 0 auto;
  flex-grow: 99;
  @media (max-width: 1200px) {
    width: 96vw;
  }
`

function AppComponent({history}) {
  return (
    <App>
      <AppContent>
        <Header history={history}/>
        <Switch />
      </AppContent>  
      <Footer />
    </App>

  );
}

export default AppComponent

switch.js:

import React from 'react'
import { Route, Switch, withRouter } from 'react-router-dom'
// Components
import Home from '../pages/home'
import About from '../pages/about'

  render () {
    return (
      <Switch>
        <Route exact path='/' component={Home} />
        <Route exact path='/about' component={About} />
        <Route component={Home} />
      </Switch>
    )
  }
}

export default withRouter(SwitchComponent)

【问题讨论】:

    标签: reactjs express heroku react-router


    【解决方案1】:

    将生产环境中的 app.get 处理程序更改为

    app.get("/*", (req, res) => {
           res.sendFile(path.join(__dirname, "../build", "index.html"), err => {
               if (err) {
                   console.log(err);
               }
           });
       });
    

    【讨论】:

      猜你喜欢
      • 2020-07-29
      • 2020-11-06
      • 2018-01-09
      • 2017-03-11
      • 2023-03-06
      • 2022-01-16
      • 2019-04-06
      • 2021-04-27
      • 1970-01-01
      相关资源
      最近更新 更多