【问题标题】:How to handle invalid routes in Nodejs?如何处理 Nodejs 中的无效路由?
【发布时间】:2021-12-26 20:53:29
【问题描述】:

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


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

这是用于路由的 react 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 将用户重定向到主页。

【问题讨论】:

  • 这是您提供 SPA 的服务器。在 SPA 服务之后,SPA 有责任进行适当的路由。显示反应路由代码。

标签: node.js reactjs error-handling routes


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2016-04-23
    • 2017-05-13
    • 2023-03-20
    • 1970-01-01
    • 2018-06-18
    • 1970-01-01
    • 1970-01-01
    • 2016-09-10
    • 1970-01-01
    相关资源
    最近更新 更多