简体   繁体   中英

How to handle invalid routes in Nodejs?

I am using the following code to handle invalid route.


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

This is react app.js code for routing

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;

but It just shows blank page while I want to redirect user to home page using Reactjs.

I used the following code instead. Its working fine

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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