为什么 React 路由不能在服务器上正常工作?

Why does React routes doesn't work on server properly?

我正在创建一个反应应用程序并遇到一些问题。我的路由在客户端(开发服务器)运行良好,但是当我通过 express 提供静态文件时,它仅适用于 '/' 路由。 '/dashboard' 没有 work.But 当我添加此行时

app.get('*', (req, res) => res.sendFile(path.join(__dirname, '../../dist/index.html')));

路由开始运行良好,但我在尝试 登录

时遇到另一个错误

Uncaught SyntaxError: Unexpected token <

这是我的快递服务器代码`

const express = require('express');
const session = require('express-session');
const passport = require('passport');
const EventbriteStrategy = require('passport-eventbrite-oauth').OAuth2Strategy;
const path = require('path');
const bodyParser = require('body-parser');
const keys = require('./config/keys');

const port = process.env.PORT || 5000;

const app = express();

app.use(express.static(path.join(__dirname, '../../dist')));
app.get('*', (req, res) => res.sendFile(path.join(__dirname, '../../dist/index.html')));


app.use(passport.initialize());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(session({
  secret: 'login',
  resave: false,
  saveUninitialized: true
}));

const strategy = new EventbriteStrategy({
  clientID: keys.eventbriteClientID,
  clientSecret: keys.eventbriteClientSecret,
  callbackURL: 'http://localhost:5000/auth/eventbrite/callback'
},
((accessToken, refreshToken, extraParams, profile) => {
  console.log(profile, 'profile');
  console.log(accessToken, 'accessToken');
  console.log(accessToken, 'accessToken');
  console.log(extraParams, 'extraParams');
}
));

passport.use(strategy);

app.get('/auth/eventbrite',
  passport.authenticate('eventbrite', {}), (req, res) => {
    console.log(res, 'rees');
  });

app.get('/auth/eventbrite/callback',
  passport.authenticate('eventbrite', { failureRedirect: '/' }),
  (req, res) => {
    if (!req.user) {
      throw new Error('user null');
    }
    res.redirect('/dashboard');
  });

app.listen(port, () => {
  console.log(`Server is up on port ${port}`);
});

这是我的路由器`

import React from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import DashboardPage from '../components/pages/DashboardPage';
import LoginPage from '../components/pages/LoginPage';
import NotFoundPage from '../components/pages/NotFoundPage';

const AppRouter = () => (
  <BrowserRouter>
    <React.Fragment>
      <Switch>
        <Route path="/" component={LoginPage} exact />
        <Route path="/dashboard" component={DashboardPage} />
        <Route component={NotFoundPage} />
      </Switch>
    </React.Fragment>
  </BrowserRouter>
);

export default AppRouter;

这是登录页面`

import React from 'react';
import { NavLink } from 'react-router-dom';

const logo = require('../../../../public/images/react.png');

const config = {
  logo,
  authUrl: ''
};

const LoginPage = props => (
  <React.Fragment>
    <header file={props} className="login-header">
      <div className="row">
        <div className="login-header__wrapper">
          <div className="login-header__logo-box">
            <NavLink to="/" role="link"><img src={config.logo} alt="logo" width="190" height="80" className="navbar__logo" /></NavLink>
          </div>
          <h1 className="login-header__heading">Welcome to Events</h1>
        </div>
      </div>
    </header>
    <main>
      <section className="register">
        <div className="row">
          <div className="register-wrapper">
            <section className="register__description">
              <h2>Events</h2>
              <p>Here you can search your favourite events and get the location on map</p>
            </section>
            <section className="register__sign-in">
              <h2>Sign in with facebook</h2>
              <div>
                <a href="/auth/eventbrite" className="btn btn_sign-in">Sign in</a>
              </div>
            </section>
          </div>
        </div>
      </section>

    </main>

我应该怎么做才能使所有路由正常工作?

通配符路由 * 是与 React Router 反应所必需的,这样服务器就不会在 React 时寻找 get/dashboard Router 改变了位置,React Router 可以继续处理路由。所以你在正确的轨道上。

然而,问题在于首先检查您的通配符路由,因此它会捕获每条路由——包括您的 /auth 路由。要解决这个问题,您可以简单地将通配符路由的控制器放在 之后 所有其他路由都已在服务器中定义。这是可行的,因为 Express 将检查从 app.js(或您命名的任何名称)文件的顶部到底部移动的路线,并在找到与请求的路线匹配的路线后立即停止。

所以只需移动这个:

app.get('*', (req, res) => res.sendFile(path.join(__dirname, '../../dist/index.html')));

所以它低于任何其他 app.getapp.post,等等。基本上它应该在正上方:

app.listen(port, () => {
  console.log(`Server is up on port ${port}`);
});