Skip to content

Instantly share code, notes, and snippets.

@frostming
Last active March 19, 2019 03:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frostming/3c2694c5e18f64ac7c17fd11178c98f5 to your computer and use it in GitHub Desktop.
Save frostming/3c2694c5e18f64ac7c17fd11178c98f5 to your computer and use it in GitHub Desktop.
Simple CORS example with Flask

A simple example of CORS & Ajax with Flask

Requirements

$ pipenv install flask flask-cors

Start development server

  1. Start flask app at port 5000
    $ FLASK_ENV=development pipenv run flask run
  2. Open another terminal and start serving static file at port 8080
    $ cd templates && python3 -m http.server 8080

Play around and see how Ajax retrieves responses from the server.

from flask import Flask, jsonify, session
from flask_cors import CORS
app = Flask(__name__)
app.config['SECRET_KEY'] = 'this is a secret'
CORS(app, supports_credentials=True)
@app.route('/login', methods=('POST',))
def login():
session['user'] = 'me'
return ''
@app.route('/logout', methods=('POST',))
def logout():
session.pop('user', None)
return ''
@app.route('/action')
def action():
if 'user' in session:
return jsonify({'message': 'You are logged in'})
else:
return jsonify({'message': 'You are not logged in'}), 401
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Login Testing</title>
</head>
<body>
<div id="logout">
<h1>Please login</h1>
<a href="javascript:void(0)" id="login-btn">Login</a>
</div>
<div id="login">
<h1>You are logged in!</h1>
<a href="javascript:void(0)" id="logout-btn">Logout</a>
</div>
<a href="javascript:void(0)" id="action-btn">Action</a>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script>
const API = "http://localhost:5000";
function isLogin() {
return fetch(`${API}/action`, {
credentials: 'include',
mode: 'cors'
}).then(resp => resp.ok);
}
$(function() {
$('#login-btn').click(e => {
e.preventDefault();
fetch(`${API}/login`, {
method: 'POST',
mode: 'cors',
credentials: 'include',
}).then(resp => {
if(resp.ok) {
$('#login').show();
$('#logout').hide();
}
});
});
$('#logout-btn').click(e => {
e.preventDefault();
fetch(`${API}/logout`, {
method: 'POST',
mode: 'cors',
credentials: 'include',
}).then(resp => {
if(resp.ok) {
$('#login').hide();
$('#logout').show();
}
});
});
$('#action-btn').click(e => {
e.preventDefault();
fetch(`${API}/action`, {
mode: 'cors',
credentials: 'include',
}).then(resp => resp.json()).then(data => {
alert(data.message);
});
});
isLogin().then(ok => {
if (ok) {
$('#login').show();
$('#logout').hide();
} else {
$('#login').hide();
$('#logout').show();
}
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment