Answer the question
In order to leave comments, you need to log in
Implementing a SIMPLE auth token between Flask and React?
Evening at home!
If you knew how this authorization token got me, I don’t understand anything, a bunch of examples in Google (of incomprehensible complexity) did not help me in this matter. And all I need is for some of the routers to be closed for guests, and for authorized ones it was open.
I have a simple flask login (no mongodb, mysql, etc.)
@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'})
Answer the question
In order to leave comments, you need to log in
So, will there be SIMPLE examples of implementing an authorization token between these two frameworks?
import React from 'react';
import Cookie from 'js-cookie';
class SimpleExample extends React.Component {
state = {
isProcessing: false,
token: Cookie.get('token'),
data: null,
};
handleSignIn = () => {
this.setState({ isProcessing: true });
fetch('/singin', {
method: 'POST',
data: JSON.stringify({ login: 'admin', pass: 'zx23ww' }),
})
.then(res => res.json())
.then(data => {
this.setState({
isProcessing: false,
token: data.token,
});
Cookie.set('token', token);
});
};
handleLogout = () => {
Cookie.erase('token');
this.setState({ token: null });
};
handleGetProtectedData = () => {
fetch('/protected'{
method: 'GET',
headers: {
Authorization: `Bearer ${this.state.token}`,
},
})
.then(res => res.json())
.then(data => {
this.setState({ data });
});
};
render() {
const { isProcessing, token } = this.state;
if (isProcessing) return <div>...initialization</div>;
const isSignedIn = !!token;
return isSignedIn ? (
<div>
<h1>You're signed in</h1>
<button onClick={this.handleLogout}>Logout</button>
<button onClick={this.handleGetProtectedData}>Get protected data</button>
</div>
) : (
<div>
<h1>You're not signed in</h1>
<button onClick={this.handleSignIn}>Sign in</button>
</div>
);
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question