S
S
Sergey Bondarenko2019-04-14 18:30:44
Flask
Sergey Bondarenko, 2019-04-14 18:30:44

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'})

What the front-end looks like (authorization form):
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;

app.js:
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'));

In general, I sat tormenting Google, and found a sensible answer, how to return certain routers to the client (let's say /home, /feed), and remove others (let's say /login), or let's say if the user is not authorized, then cut off part of the site's functionality? I read about tokens, but did not understand how they can be used in page routing.
BIG THANKS in advance!
Forgive me for uploading such questions, but this has stumped me, maybe there will be examples?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-04-14
@lietryit

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>
    );
  }
}

Still, I advise you to use redux. And as an HTTP client - axios.
When using redux, the initialization process is taken out in action:
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 question

Ask a Question

731 491 924 answers to any question