【问题标题】:Cannot GET (path) Reactjs, nodejs无法获取(路径)Reactjs,nodejs
【发布时间】:2021-06-14 07:09:03
【问题描述】:

我正在尝试从 Nodejs 提供我的 react 应用程序,但我收到了一个 GET 错误,这很奇怪,因为当我运行 npm start 并运行 react start 脚本时一切正常,但是一旦我使用 node.js 它不起作用。此外,如果我通过输入或尝试向后导航来导航到路线,则会引发错误。例如,当您第一次导航到主页时,它会将您带到登录页面,如果我转到另一个页面然后回击它会引发 GET 错误,即使它事先工作。

Node.js 服务器

const express = require('express');
const cors = require('cors');
const path = require('path');
const app = express();

require('dotenv').config()

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



app.get('/', async (req,res) => {

    res.sendFile(path.join(__dirname, 'build', 'index.html'));
    
    });




    app.listen(3000, () => {
        console.log(`Server listening on 3000`);
    });

反应 index.js

*/
import React from "react";
import ReactDOM from "react-dom";
import { createBrowserHistory } from "history";
import { Router, Route, Switch, Redirect } from "react-router-dom";
import { Auth0Provider } from "@auth0/auth0-react";

// core components
import Admin from "layouts/Admin.js";
import Authentication from 'layouts/Authentication';
import DashboardPage from "views/Dashboard/Dashboard.js";
import UserProfile from "views/UserProfile/UserProfile.js";

import "assets/css/material-dashboard-react.css?v=1.9.0";

const hist = createBrowserHistory();

ReactDOM.render(
  <Auth0Provider
  domain={`${process.env.REACT_APP_Auth0_Domain}`}
  clientId={`${process.env.REACT_APP_Auth0_ClientID}`}
  redirectUri={`http://localhost:3000/dashboard`}
  >
  <Router history={hist}>
    <Switch>
      <Route path="/login"  component={Authentication} />
      <Route path="/dashboard" component={DashboardPage} />
      <Route path="/user"  component={UserProfile} />
      <Redirect from='/' to='/login' />
    </Switch>
  </Router>,
  </Auth0Provider>,
  document.getElementById("root")
);

Routes.js

// @material-ui/icons
import Dashboard from "@material-ui/icons/Dashboard";
import Person from "@material-ui/icons/Person";

// core components/views for Admin layout
import DashboardPage from "views/Dashboard/Dashboard.js";
import UserProfile from "views/UserProfile/UserProfile.js";
import Authentication from './layouts/Authentication';

const dashboardRoutes = [
  {
    path: "/dashboard",
    name: "Invoice Dashboard",
    icon: Dashboard,
    component: DashboardPage,
  },
  {
    path: "/login",
    name: "Login",
    icon: Dashboard,
    component: Authentication
  },
  {
    path: "/user",
    name: "User Profile",
    icon: Person,
    component: UserProfile,
  }
];

export default dashboardRoutes;

【问题讨论】:

  • Routes.js 文件是否相关或在任何地方使用?它似乎重复了 index.js 文件中定义的路由。您是否尝试使用服务器端渲染 (SSR)? reactjs.org/docs/react-dom-server.html
  • 听不懂他想说什么,能不能说清楚一点
  • 路由文件在另一个地方用于帮助在导航栏中制作项目,仅此而已。是的,尝试进行服务器端渲染,我所有的反应应用程序都使用这个设置,这是我第一次遇到这个问题时不知道我错过了什么。

标签: javascript node.js reactjs authentication react-router


【解决方案1】:

此行为来自您在 node.js 服务器中的 express 应用程序。

查看您的陈述

app.get('/', async (req,res) => {
  res.sendFile(path.join(__dirname, 'build', 'index.html')); 
});

当您请求路径 '/' 时,您的应用只会返回 index.html 文件。基本上,您的反应路由器仅通过对'/' 的初始请求建立 - 允许反应Link(例如)元素在此后正确路由。这就解释了为什么输入深层链接(例如'/example-path')并点击返回按钮会引发错误。

构建您的快速路由以处理特定 URL,并为所有其他 URL 返回 index.js 文件。这将允许 react 路由器处理您的前端路由,并且仍然允许 express 处理后端路由。

// An example api endpoint that returns a list of items
app.get('/api/getList', (req, res) => {
    var list = ["item1", "item2", "item3"];
    res.json(list);
    console.log('Sent list of items');
});

// Handles any requests that don't match the ones above
app.get('*', (req, res) =>{
    res.sendFile(path.join(__dirname, 'build', 'index.html')); 
});

【讨论】:

  • 感谢您的宝贵时间,所以如果我理解正确,如果我使用通配符 * 它应该涵盖其他路线,例如 /dashboard?
  • 应该,是的。
  • 完美,我只是把它放在我所有其他路线下,谢谢。
猜你喜欢
  • 2020-05-25
  • 2020-01-02
  • 1970-01-01
  • 2016-01-11
  • 1970-01-01
  • 2017-01-15
  • 1970-01-01
  • 2017-12-19
  • 2019-10-17
相关资源
最近更新 更多