Answer the question
In order to leave comments, you need to log in
How to pass a router from flask to react?
Hello, today I did authorization of users. So, I didn’t understand how to make one part of the site be displayed for the guest, and another part for the authorized ones.
I created a regular function that takes data from the front-end and compares it with the user's data, and if the data that came in is correct, then the server returns a message to the client.
from flask import Flask, jsonify, request
@app.route('/log', methods = ['POST'])
def post():
if request.form.get('login') == 'admin' and request.form.get('pass') == 'zx23ww':
return jsonify({'type':'success','msg':'success'})
return jsonify({'type':'error','msg':'error'})
import React, { Component } from 'react';
import $ from 'jquery';
class Auth extends Component {
componentDidMount() {
document.title = 'Авторизация';
$('#sub-log').click(function(event, result) {
event.preventDefault();
$.post($('#log-form').attr('action'), $('#log-form').serialize(), function(result) {
console.log(result);
var msg = JSON.stringify(result);
$('#msg').html(msg).show().delay(5000).hide(1);
});
});
}
render() {
return (<code lang="html">
<div>
<form action = 'http://localhost:5000/log' method = 'post' id = 'log-form' className = 'log-form-active'>
<input type="text" name="login" placeholder="Ваш логин"/>
<input type="password" name="pass" placeholder="Ваш пароль"/>
<button id = 'sub-log'>CLICK</button>
</form>
<div id = 'msg'></div>
</div></code>);
}
}
export default Auth;
import React, { Component }from 'react';
import * as serviceWorker from './serviceWorker';
import ReactDOM from 'react-dom';
import {BrowserRouter as Router, Route} from 'react-router-dom';
import Auth from './Auth';
import Feed from './Feed';
class Main extends Component {
render() {
return (<code lang="html">
<Router>
<div id = 'content'>
<Route path='/' exact component={Auth} />
<Route path='/feed' exact component={Feed} />
</div>
</Router></code>);
}
}
ReactDOM.render(<Main />, document.getElementById('main'));
Answer the question
In order to leave comments, you need to log in
1. Cut out from the jQuery project.
2. Read the React documentation on how to work with forms.
3. In a good way, add Redux to the project.
A simple example of solving your problem without using Redux:
class Main extends Component {
state = {
isInitializing: true,
isSignedIn: false,
user: null,
};
async componentDidMount() {
// тут достаем токен, например, из cookie
const token = storage.get(TOKEN_KEY);
if (token) {
// тут сетим токен в заголовки по-умолчанию библиотеки для HTTP-запросов
api.setHeader('Authorization', `Bearer ${token}`);
const user = await api.getUser();
this.setState({ user, isSignedIn: true, isInitializing: false });
} else {
this.setState({ isInitializing: false });
}
}
render() {
const { isSignedIn, isInitializing } = this.state;
// на время инициализации показываем ProgressBar
if (isInitializing) return <ProgressBar />;
return (
<code lang="html">
<Router>
<div id = 'content'>
{isSignedIn ? (
<React.Fragment>
<Route path='/feed' exact component={Feed} />
<Redirect from='/' to="/feed" />
</React.Fragment>
) : (
<React.Fragment>
<Route path='/' exact component={Auth} />
<Redirect from="/feed" to="/" />
</React.Fragment>
)}
</div>
</Router>
</code>
);
}
}
const store = configureStore();
store.dispatch(init()); // начинаем процесс инициализации еще до монтирования приложения
ReactDOM.render(
<Provider store={store}>
<Main />
</Provider>, document.getElementById('main'),
);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question