Home > Software engineering >  Redirect in react login system
Redirect in react login system

Time:10-14

I wrote a code for login system (backend) which checks whether the username and password are valid or not. Everything is working but I don't know how to do automate redirect to /dashboard. Client side is running on Port 3000, and server on Port 3001 and I am getting error because script finding the /dashboard on localhost:3001. Can anyone help me?

app.post("/login", (req, res) => {
    // Capture the input fields
    const username = req.body.username;
    const password = req.body.password;
    // Ensure the input fields exists and are not empty
    if (username && password) {
      // Execute SQL query that'll select the account from the database based on the specified username and password
      db.query(
        "SELECT * FROM users WHERE username = ? AND password = ?",
        [username, password],
        function (error, results, fields) {
          // If the account exists
          if (results.length > 0) {
            
            console.log('Valid')
          } else {
            console.log('Invalid')
          }
          res.end();
        }
      );
    } else {
      res.send("Please enter Username and Password!");
      res.end();
    }
  });

CodePudding user response:

It seems that you want to redirect to /dashboard endpoint once you are able to login. you can use window.location.href="/dashboard"

or

you can also use Routes and Navigate from react-router-dom

Please check this How can I redirect in React Router v6?

CodePudding user response:

If you are doing AJAX calls then you can use express js proxy configuration in your react project. So that will redirect localhost:3000/api calls to localhost:3001. So you don't need to worry about CORS.

const express = require('express');
const app = express();
const { createProxyMiddleware } = require('http-proxy-middleware');

app.use(createProxyMiddleware('/api/**', {
  target: 'http://127.0.0.1:3001',
}));

if you have own login page in node.js and you want to redirect to client then you need to pass url as query string parameter ?url= and in your code get query string param url and use node redirect function to redirect. Make sure you use full URL including domain and port so it will redirect to another page instead of finding on your nodejs server.

res.redirect('http://localhost:3000/dashboard');
  • Related