首页 > 解决方案 > 无法使用 react-router 和 express 重新加载或手动键入页面路由

问题描述

我正在使用服务器端的 Express 路由器设置带有 React 路由器的单页应用程序(用于使用 React 路由器为第一个索引页面提供服务,然后等待 API 请求)。目前我只有 2 条路线:'/' 和 '/history'

-单击主页上的“历史”链接可以毫无问题地到达那里。

- 手动输入“/history”路线使浏览器永远保持加载状态。

- 在“/history”上重新加载页面使浏览器永远保持加载状态。

我该如何解决这个问题?

我尝试在 express 上重新安排路线,之后我尝试设置 app.all('*') 方法来处理所有请求。最后我尝试用 app.get 更改 app.all ...,但这些都没有帮助我。

我的 index.js(用于快速路由器):

    /*Express Server*/
    const express = require('express');
    const app = express();
    const morgan = require('morgan');
    const path = require('path');
    const bodyParser = require('body-parser');

    const { mongoose } = require('./database');

    //settings
    app.set('port', process.env.PORT || 3000);

    //middleware
    app.use(morgan('dev'));
    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(bodyParser.json());

    //routes
    app.use('/api/month',require('./routes/monthly.routes'));

    app.use('/history',require('./routes/history.routes'));

    //static files
    app.use(express.static(path.join(__dirname, 'public')))

    app.get(async (req,res)=>{
        await res.sendFile(path.join(__dirname, '/public/index'), (err)=> {
        if (err) {
          res.status(500).send(err)
        }
    })
    });

    //Start server
    app.listen(app.get('port'), ()=>{
        console.log(`Server listening on ${app.get('port')}`);
    });

我的 app.js 的路由器部分(用于反应路由器):

    import React, { Component } from 'react';
    import ReactDom from 'react-dom';
    import { BrowserRouter, Route, Switch } from 'react-router-dom';
    import Axios from 'axios';

    import Home from './Home'
    import Latest from './Latest'

    class App extends Component {
        constructor(props) {
            super(props);
            this.state = {
                RecentExpenses: [],
                monthState: null,
                Total: 0,
                Today: null
            }
        };

        render() {
            return (
                    <BrowserRouter>
                        <Switch>
                            <Route exact path='/' render={(props) => <Home {...props} Today={this.state.Today} Total={this.state.Total} RecentExpenses={this.state.RecentExpenses} />}  />
                            <Route exact path='/history' render={(props) => <Latest {...props} Recent={this.state.RecentExpenses} month={this.state.monthState} />} />
                        </Switch>
                    </BrowserRouter>
            )
        }
    }

    ReactDom.render(<App/>, document.getElementById('app'));

我期望总是从服务器接收相同的文件,所以反应路由器可以作为导航路由器。但它会一直加载到节点控制台中:

(node:8756) UnhandledPromiseRejectionWarning: Error: Cannot find module 'html'
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:571:15)
at Function.Module._load (internal/modules/cjs/loader.js:497:25)
at Module.require (internal/modules/cjs/loader.js:626:17)
at require (internal/modules/cjs/helpers.js:20:18)

标签: node.jsreactjsexpressreact-routersingle-page-application

解决方案


在您的 index.js 上,您可以替换它:

app.use(express.static(path.join(__dirname, 'public')))

app.get(async (req,res)=>{
    await res.sendFile(path.join(__dirname, '/public/index'), (err)=> {
    if (err) {
      res.status(500).send(err)
    }
  })
});

为了那个原因:

app.use(express.static(`${process.cwd()}/public/`))

app.get('*', async (req, res) => {
    await res.sendFile(`${process.cwd()}/public/index.html`, (err) => {
        if (err) {
            res.status(500).send(err)
        }
    })
});

您应该能够毫无问题地访问 /history。


推荐阅读