привет, ребята, я новичок в reactjs, поскольку я пытался аутентифицировать пользователя с помощью узла js backend, хотя я могу распечатать json msg в консоли, но не могу перенаправить его на домашнюю страницу. Может кто-нибудь помочь .. вот код login.js (реакция на стороне клиента) ...
import React, { Component } from 'react';
import './Login.css';
import {Link, Redirect} from 'react-router-dom';
import {history} from 'history';
class AddLogin extends Component {
constructor(props)
{
super(props)
this.state = {
user_email : "",
user_password: "",
user_remember : ""
}
}
change = e =>
{
this.setState({
[e.target.name] : e.target.value
})
}
getWebsite = () => {
fetch("/").then(console.info(this.state));
};
onSubmit = e =>
{
e.preventDefault();
//console.info(this.state);
this.setState({
user_email : "",
user_password: "",
user_remember : ""
})
fetch('login', {
method : "POST",
headers : {
"Content-Type" : "application/json; charset=utf-8"
},
body : JSON.stringify(this.state)
})
.then(function(response){return response.json();})
.then(function(json){
if (json.success===true){
console.info(json);
// this.props.onRouteChange('/');
this.props.history.push("/")
}
else{
console.info("data 404");
}})
.then(this.getWebsite)
}
render() {
return (
<div>
<body class = "my-login-page">
<section class = "h-100">
<div class = "container h-100">
<div class = "row justify-content-md-center h-100">
<div class = "card-wrapper">
<div class = "brand">
<img src = "img/logo.jpg" />
</div>
<div class = "card fat">
<div class = "card-body">
<h4 class = "card-title">Login</h4>
<form method = "POST">
<div class = "form-group">
<label for = "email">E-Mail Address</label>
<input id = "email" type = "email" class = "form-control" name = "user_email" value = {this.state.user_email} onChange = {e => this.change(e)} required autofocus />
</div>
<div class = "form-group">
<label for = "password">Password
<a href = "forgot.html" class = "float-right">
Forgot Password?
</a>
</label>
<input id = "password" type = "password" class = "form-control" name = "user_password" value = {this.state.user_password} onChange = {e => this.change(e)} required data-eye />
</div>
<div class = "form-group">
<label>
<input type = "checkbox" name = "user_remember" value = {this.state.user_remember} onchange = {e => this.change(e)}/> Remember Me
</label>
</div>
<div class = "form-group no-margin">
<button class = "btn btn-primary btn-block" onClick = {e => this.onSubmit(e)} >
Login
</button>
</div>
<div class = "margin-top20 text-center">
Don't have an account? <Link to = "/Register">Create One</Link>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</section>
</body>
</div>
);
}
}
export default AddLogin;
вот код серверной части (код node.js ....)
var express = require('express');
var router = express.Router();
var con = require('./db');
var func = require('./func.js');
var edo=require('./edonomix.js');
// router.get('/',function(req, res, next)
// {
// if (req.session.adminid)
// {
// res.json({"success":true,'msg':'admin home page'});
// }
// else
// {
// res.json({"success":true,'msg':'admin login page'});
// }
// });
router.post('/',function(req,res)
{
if (req.session.adminid)
{
//data at home page
res.json({"success":true,'msg':'admin home page'});
}
else
{
req.check('user_password','invalid password at least 6 character required').isLength({min:6,max:100});
req.check('user_email','invalid username').isLength({min:2,max:100}).isEmail();
var verrs=req.validationErrors();
if (verrs)
{
res.json({ success:false,msg: verrs[0].msg,});
}
else
{
console.info(req.ip);
var admin =
{
email:req.body.user_email,
password:req.body.user_password
};
con.query("select * from admin where email_id=?",admin.email,function(err,result,fields)
{
if (err)
{
console.info(err);
res.json({'success':false});
}
else if (result.length==1)
{
if (edo.hashPassword(admin.password)===result[0].password)
{
var hour = 3600000;
req.session.cookie.expires = new Date(Date.now() + hour);
req.session.cookie.maxAge = hour;
req.session.adminid=result[0].admin_id;
res.json({'success':true,'msg':'admin home page'})
}
else
{
//wrong pass
res.json({"success":true,'msg':'admin login page invalid email/password'});
}
}
else
{
res.json({"success":true,'msg':'admin login page wrong email'});
}
});
}
}
});
module.exports = router;
и вот код App.js (здесь код реакции) ...
import React, { Component } from 'react';
// import logo from './logo.svg';
import './App.css';
import Header from './components/Header/Header';
import Footer from './components/Footer/Footer';
import Home from './components/Home/Home';
import Sidebar from './components/Sidebar/Sidebar';
import AddProduct from './components/Product/AddProduct';
import ProductTable from './components/Product/ProductTable';
import AddBlog from './components/Blog/AddBlog';
import AddUser from './components/User/AddUser';
import AddPartner from './components/Partner/AddPartner';
import AddForms from './components/Forms/AddForms';
import Signin from './components/Login/AddLogin';
import Register from './components/Login/Register';
import Navigation from './components/Navigation';
import AddEquipment from './components/Equipment/AddEquipment';
import ViewEquipment from './components/Equipment/ViewEquipment';
import AddCustomer from './components/Customer/AddCustomer';
import CustomerTable from './components/Customer/CustomerTable';
import Admin from './components/Admin/Admin';
import AMC from './components/AMC/AMC';
import Complaint from './components/Complaint/Complaint';
import Employee from './components/Employee/Employee';
import Profile from './components/Profile/Profile';
import Schedule from './components/Schedule/Schedule';
import Site from './components/Site/Site';
import Zone from './components/Zone/Zone';
import { Route } from 'react-router-dom';
class App extends Component {
constructor() {
super();
this.state = {
route: 'signin',
isSignedIn: false,
}
}
onRouteChange = (route) => {
if (route === 'signout') {
this.setState({isSignedIn: false})
} else if (route === '/') {
this.setState({isSignedIn: true})
console.info(this.state.route);
}
else{
console.info('thi is else');
}
this.setState({route: route});
}
render() {
const { isSignedIn, route } = this.state;
return (
<div>
<Navigation isSignedIn = {isSignedIn} onRouteChange = {this.onRouteChange} />
{ route === '/'
?
<div>
<Header />
<Sidebar />
<Route path = "/" exact component = {Home} />
<Route path = "/AddProduct" exact = {true} component = {AddProduct} />
<Route path = "/ProductTable" exact = {true} component = {ProductTable} />
<Route path = "/AddBlog" exact = {true} component = {AddBlog} />
<Route path = "/AddUser" exact = {true} component = {AddUser} />
<Route path = "/AddPartner" exact = {true} component = {AddPartner} />
<Route path = "/AddForms" exact = {true} component = {AddForms} />
<Route path = "/Register" exact = {true} component = {Register} />
<Route path = "/AddEquipment" exact component = {AddEquipment} />
<Route path = "/ViewEquipment" exact component = {ViewEquipment} />
<Route path = "/AddCustomer" exact component = {AddCustomer} />
<Route path = "/CustomerTable" exact component = {CustomerTable} />
<Route path = "/Admin" exact = {true} component = {Admin} />
<Route path = "/AMC" exact = {true} component = {AMC} />
<Route path = "/Complaint" exact = {true} component = {Complaint} />
<Route path = "/Employee" exact = {true} component = {Employee} />
<Route path = "/Profile" exact = {true} component = {Profile} />
<Route path = "/Schedule" exact = {true} component = {Schedule} />
<Route path = "/Site" exact = {true} component = {Site} />
<Route path = "/Zone" exact = {true} component = {Zone} />
</div>
: (
route === 'signin'
? <Signin loadUser = {this.loadUser} onRouteChange = {this.onRouteChange}/>
: <Register loadUser = {this.loadUser} onRouteChange = {this.onRouteChange}/>
)
}
<Footer />
</div>
);
}
}
export default App;



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Похоже, вы не отслеживаете состояние? Я бы посоветовал привлечь redux. Redux - это простой способ отслеживать состояние, не затрагивая серверную часть каждый раз, когда вам нужны данные. Поначалу немного сложно обдумывать, но как только вы это сделаете, вы никогда не вернетесь назад.
Redux позволит вам отслеживать ваш jwt или что-то еще, что вы используете для проверки вашей аутентификации во внешнем интерфейсе.