Solving the CORS problem with flask (Python)
Solving the CORS problem with flask (Python)

Solving the CORS problem with flask (Python)

Date
Feb 2, 2023
Tags
small-scale
backend
Python
Install flask-cors by running:
pip3 install -U flask-cors
server.py
from flask import Flask from flask_cors import CORS, cross_origin app = Flask(__name__) cors = CORS(app) app.config['CORS_HEADERS'] = 'Content-Type' @app.route("/") @cross_origin() def helloWorld(): return "Hello, cross-origin-world!" if __name__ == "__main__": app.run(host='0.0.0.0', port=8000, debug=True)
 
alternative if you want to send cookies along the payload back and forth:
just add support_credentials=True
from flask import Flask, jsonify from flask_cors import CORS, cross_origin app = Flask(__name__) CORS(app, support_credentials=True) @app.route("/") @cross_origin(supports_credentials=True) def helloWorld(): return "Hello, cross-origin-world!" if __name__ == "__main__": app.run(host='0.0.0.0', port=8000, debug=True)
 
run: python3 server.py
 
Usage in front-end:
const fetchHelloWorld: async () => { try { const requestURL = `http://localhost:8000`; const res = fetch(requestURL) .then((response) => response.json()) .then((data) => { return data; }); return res; } catch (e) { console.log(e); } }
 
 

Read my other posts:

Useful links for your Notion Website
Useful links for your Notion Website
 

References: