'Routing different urls depending on function using Javascript/React
I want to route route different urls depending on the login, which is called by axios in this code:
import React, {Component} from "react";
import axios from "axios";
import "./ComponentStyles.css";
class Login extends Component {
state = {
username: "",
password: ""
}
handleChange = ({target}) => {
const { name, value } = target;
this.setState({
[name]:value
});
};
Login = (event) => {
event.preventDefault();
const User = {
username: this.state.username,
password: this.state.password
}
axios({
url:"/api/login",
method: "POST",
data: User
})
.then((res) => {
if (res === true) {
console.log('Logged in!');
window.location = '/Menu';
}
else {
window.location = '/';
console.log('Failure. Could not Login.');
})
.catch((error) => {
console.log(error);
window.location = '/';
})
};
// more code
}
in this, I want to set the window.location depending on the result of the function user_authMySQL, which is in this other code:
const express = require("express");
const router = express.Router();
// some code
router.post('/login', async (req, res) => {
const User = req.body; // Object type: User
var resultTemp = false;
// This function recieves a username, password, and callback function
// result in callback function is true if login succeeds, otherwise it's false
await user_authMySQL(User.username, User.password, function (result) {
resultTemp = result;
console.log(resultTemp); // To see what's stored
if (resultTemp === false )
console.log("Cannot login, data is invalid.");
else console.log("Loggin in!");
});
console.log(resultTemp + ' = resultTemp'); // This
res.json();
});
When I run it and use invalid login data, this is what the terminal result:
[Server] false = resultTemp
[Server] POST /api/login 200 - - 5.987 ms
[Server] false
[Server] false
[Server] Cannot login, data is invalid.
And when correct login data is used, this is the result:
[Server] false = resultTemp
[Server] POST /api/login 200 - - 1.258 ms
[Server] true
[Server] true
[Server] Loggin in!
The problem is, the app always does window.location = '/' but doesn't do the console.log() for any of the conditions in the
.then((res) => {
if (res === true) {
console.log('Logged in!');
window.location = '/Menu';
}
else {
window.location = '/';
console.log('Failure. Could not Login.');
})
.catch((error) => {
console.log(error);
window.location = '/';
})
I don't know how to route the different urls depending on the function, and any help is welcome :)
Solution 1:[1]
well you have several problems with your code and I highly recommend that you reconsider how you do this login otherwise you need to send the "true" value from the server-side so you can test it later on res.json(true) in your case
after that you can test it by res.data === true
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | mouheb |
