I am new to react and I tried to make Protected routes which works perfectly on local but on server it gives the error.
my Code is as follows
Protected Route
import React from "react";
import { Redirect, Route } from "react-router-dom";
function ProtectedRoute({ component: Component, ...restOfProps }) {
const token = localStorage.getItem("token");
const userId = localStorage.getItem('userId');
return (
<Route
{...restOfProps}
render={(props) =>
token && userId ? <Component {...props} /> : <Redirect to="/login" />
}
/>
);
}
export default ProtectedRoute;
Main Component
import React, { Component } from "react";
import Navbar from "../Shared/Navbar";
import List from "./ListComponent";
import Login from "./LoginComponent";
import { BrowserRouter as Router, Route, Switch, Redirect } from "react-router-dom";
import Dashboard from "./Dashboard";
import Item from "./Item";
import ProtectedRoute from "./ProtectedRoute";
class Main extends Component {
constructor(props) {
super(props);
// this.state = {
// token: '',
// userId: ''
// }
// this.handleData = this.handleData.bind(this);
this.handleLogout = this.handleLogout.bind(this);
}
// handleData(token, userId) {
// this.setState({ token: token, userId: userId });
// localStorage.setItem('token', token);
// localStorage.setItem('userId', userId);
// window.location='/';
// }
handleLogout(){
this.setState({token: ''})
this.setState({userId:'' })
localStorage.setItem('userId','')
localStorage.setItem('token', '');
}
render() {
return (
<>
<Router>
<Navbar handleLogout={this.handleLogout}/>
<Switch>
<ProtectedRoute exact path ={["/home","/"]} component={Dashboard} />
<ProtectedRoute exact path ="/list" component={List} />
<ProtectedRoute exact path ="/item" component={Item} />
<ProtectedRoute exact path ="/item/:id" component={Item} />
{/*<Route path="/login" component={Login}/>*/}
{
localStorage.getItem('token') === '' && localStorage.getItem('userId') === ''
?<Route exact path="/login" component={Login} />
:<Redirect to='/'/>
}
</Switch>
</Router>
</>
);
}
}
export default Main;
Here when i comment protected Route condition it works on server but the login page is accessible.
LoginComponent
import React, {Component} from "react";
import api from "../../http-common";
class Login extends Component {
constructor(props) {
super(props);
this.state = {
username: '',
password: '',
// tokenData: ''
}
this.handleLogin = this.handleLogin.bind(this);
this.handleUsername = this.handleUsername.bind(this);
this.handlePassword = this.handlePassword.bind(this);
}
handleUsername(e){
if(e.target.value.length > 0){
this.setState({username: e.target.value})
}
}
handlePassword(e){
this.setState({password: e.target.value})
}
handleLogin(e){
e.preventDefault();
this.login(this.state.username, this.state.password);
}
async login(username, password) {
const formData = new FormData();
formData.append('username', username);
formData.append('password',password);
await api.post('/api/login', formData)
.then(response => {
if (response.status === 200 && response.data.token !== '') {
// console.log(response.data)
localStorage.setItem('token', response.data.token);
localStorage.setItem('userId', response.data.userId);
window.location='/'
// this.setState({tokenData: response.data.token});
// this.props.handleData(this.state.tokenData, this.state.username);
} else if (response.status === 200 && response.data.token === '' && response.data.message === 'User not Found') {
alert(response.data.message)
} else if (response.status === 200 && response.data.token === '' && response.data.message === 'User is not valid') {
alert(response.data.message)
} else {
console.log(response.statusText);
}
})
.catch((error) => console.log(error))
}
render() {
return (
<>
<form onSubmit={this.handleLogin}>
<div className="container">
<div className="d-flex justify-content-center mt-3">
<div className="card mt-3 mx-3 px-3 py-3">
<div className="mx-1">
<div className="form-group row">
<label htmlFor="username" className="mr-2">Username</label>
<div className="m-auto">
<input
type="text"
id="username"
name="username"
className="form-control mb-3"
placeholder="Username"
required="required"
onChange={this.handleUsername}
/>
</div>
</div>
<div className="form-group row">
<label htmlFor="password" className="mr-2">Password</label>
<div className="mx-auto">
<input
type="password"
id="password"
name="password"
className="form-control"
placeholder="Password"
required="required"
onChange={this.handlePassword}
/>
</div>
</div>
<div className="form-group">
<button type="submit" className="btn btn-primary btn-block">Log in</button>
</div>
</div>
</div>
</div>
</div>
</form>
</>
);
}
}
export default Login;
Please Help, Thank You.