Express服务器和React-Router表现异常

时间:2019-06-20 19:06:45

标签: node.js reactjs express react-router

我目前正在使用react,react-router和express。使用webpack捆绑并与webpack同时运行webpack-dev-server。

在没有路径的情况下加载应用程序('http://localhost/')时,react-router链接重定向可以正常工作,并显示带有更新URL的页面。尝试通过指定路径('/ login')访问它们时,将提供dist index.html,但页面为空白,没有错误。

以下是我的服务器索引

const express = require('express');
const logger = require('morgan');
const bodyParser = require('body-parser');
const path = require('path');

const app = express();
app.use(express.static(path.resolve('dist')));
app.use(express.static(path.resolve('public')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

app.use('/api', require('./routes/creation'));
app.use('/', require('./routes/login'));

app.get('*', (request, response) => {
    response.sendFile(path.resolve('dist', 'index.html'));
});

和App.js

import React, { Component } from 'react';
import './Styling/app.css';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import LoginPage from './Components/Login/LoginPage';
import ResetPage from './Components/Login/ResetPage';
import RegisterPage from './Components/Login/RegisterPage';

export default class App extends Component {
  render() {
    return (
      <Router>
        <Switch>
          <Route exact path="/" component={LoginPage} />
          <Route path="/login" component={LoginPage} />
          <Route path="/reset" component={ResetPage} />
          <Route path="/register" component={RegisterPage} />
          <Route component={LoginPage} />
        </Switch>
      </Router>
    );
  }
}

项目目录

Project
 |
 +-- dist
 |   |
 |   -bundle.js
 |   -index.html
 |
 +-- public
 |  |  
 |  |-- index.html
 |    
 +-- src
 |  |  
 |  --- client /... App.js
 |  --- server /... index.js

我无法弄清楚是什么原因造成的,非常感谢您的帮助

1 个答案:

答案 0 :(得分:0)

创建React App文档说,当需要通过客户端路由提供服务时,应使用类似于以下代码的内容。

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

 -app.get('/', function (req, res) {
 +app.get('/*', function (req, res) {
     res.sendFile(path.join(__dirname, 'build', 'index.html'));
 });

Create React App