简体   繁体   English

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

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

i am creating an react application and have some problems. 我正在创建一个反应应用程序,并且有一些问题。 My routes work well in the client side (dev-server) , but when i serve static files through express, it only works '/' route . 我的路由在客户端(dev-server)上运行良好,但是当我通过express服务静态文件时,它仅适用于'/' route。 '/dashboard' doesn't work.But when i add this line '/ dashboard'不起作用。但是当我添加此行时

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

routing starts to work well , but i am getting another error trying to SIGN IN 路由开始运作良好,但是尝试登录时出现另一个错误

Uncaught SyntaxError: Unexpected token < 未捕获到的SyntaxError:意外令牌<

This is my express server code ` 这是我的快递服务器代码

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}`);
});

And this is my routers ` 这是我的路由器`

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;

And here is the login page ` 这是登录页面`

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>

What should i do to make all the routes work properly ? 我应该怎么做才能使所有路线正常工作?

The wildcard route, * , is required for react with React Router so that the server doesn't go looking for a get with a route that matches /dashboard when React Router changes the location and instead React Router can continue to handle the routes. 与React Router进行交互时需要通配符路由* ,以便当React Router更改位置时服务器不会寻找与/dashboard匹配的路由get ,而React Router可以继续处理路由。 So you're on the right track there. 因此,您处在正确的轨道上。

However the issue is that your wildcard route is checked first so it's catching every single route—including your /auth routes. 但是,问题在于,首先检查了通配符路由,以便它捕获每个单独的路由,包括/auth路由。 To fix this, you can simply put the controller for the wildcard route after all other routes have been defined in the server. 要解决此问题,您只需在服务器中定义了所有其他路由之后 ,就可以将通配符路由的控制器放入控制器。 This works because Express will check routes moving from the top to bottom of the app.js (or whatever you've named it) file and stops as soon as it finds one that matches the requested route. 之所以app.js ,是因为Express会检查从app.js (或您命名的文件)文件的顶部到底部移动的路由,并在找到与请求的路由匹配的路由时立即停止。

So just move this: 因此,只需移动此:

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

so that it's below any other app.get or app.post , etc. Basically it should go right above: 因此它位于任何其他app.getapp.post等下方。基本上,它应该位于上方:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM