如何处理 Nodejs 中的无效路由?

How to handle invalid routes in Nodejs?

我正在使用以下代码来处理无效路由。


app.use(express.static("client/build"));
app.use("/api/v1/users", userRouter);
app.get("*", (req, res) => {
  res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
});

这是用于路由的反应 app.js 代码

import React from "react";
import "./App.css";
import Home from "./mainPages/home";
import Register from "./components/authentication/register";
import Signin from "./components/authentication/signin";
import ForgotPassword from "./components/authentication/forgotPassword";
import List from "./mainPages/list";
import Navbar from "./components/navbar/navbar";
import Details from "./mainPages/details";
import UpdatePassword from "./components/authentication/updatePassword";
import { Route, Switch } from "react-router-dom";
import NotFound from "./components/notfound/notfound";
import ResetPassword from "./components/authentication/resetPassword";

function App() {
  

  return (
    <div className="app">
      <Navbar/>
      <Switch>
        <Route
          exact
          path="/"
          component={() => (
            <Home />)}/>
    
        <Route path="*">
          <NotFound />
        </Route>
      </Switch>
    </div>
  );
}

export default App;

但是当我想使用 Reactjs 将用户重定向到主页时它只显示空白页面。

我改用了以下代码。工作正常

app.get("*", (req, res) => {
  res.redirect(`${req.protocol}://${req.get("host")}`);
});