简体   繁体   中英

ExpressJS: Redirect to an URL handled by client-side

I'm using ExpressJs for backend and ReactJS for frontend. The server is running on localhost:3000, the client is runnning on localhost:8080. I want to redirect user to Chat page after they have successfully logged in. So I have the code in server:

(req, res) => {
  //doing some authenticate actions up here
  if (/*successful*/) {
    //some actions here
    res.redirect("/chat");
  }

  //actions on failure down here
};

But after logging in to the account, I get this error

GET http://localhost:8080/chat 404 (Not Found)

The http://localhost:8080/chat is exists and it is handled by client-side, if I type it in address bar and go, I still can access the Chat page.

I also have the code that handles any request not matching server routes, so that request can be sent to client for handling:

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

What is wrong with my code? Did I miss something?

You should redirect the user after a successful response from the API. It is not better handled by the back-end because you have a single page application, which technically has no additional pages that the server is aware of, which is why you are getting the 404 error when trying to redirect to http://localhost:8080/chat . It is only aware of your index.html file which serves your bundles react code. The reason you are able to type in /chat into the address bar is because your UI is set up to handle requests from the router you are using. It is not the server directing you there.

It should be simple, here's an example:

logUserIn = async (userData) => {
  const isAuthed = await authenticateUser(userData)
  if (isAuthed) {
    this.props.history.push('/chat');
  } else {
    console.log('User not found!');
  }
}

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