0

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();
    }
  });
Tanish Gupta
  • 400
  • 2
  • 8
  • 20
  • Are you running two different servers? Can you please share the server connection code too – Tanish Gupta Oct 09 '22 at 15:56
  • No, one is live server from react (npm start) but my backend is on server (node index.js) index.js is backend file i have structure client and server folder – Jakub Polański Oct 09 '22 at 16:05
  • You need to allow cross-origin requests. If you are working on express server you can install the cors dependency using `npm i cors` then use that cors `app.use(cors());` – Tanish Gupta Oct 09 '22 at 16:27

2 Answers2

0

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?

Tanish Gupta
  • 400
  • 2
  • 8
  • 20
0

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');
Dhaval Gajjar
  • 2,508
  • 1
  • 2
  • 13