Python

Enable CORS in Flask app

In this post I will show you how to enable CORS (Cross Origin Resource sharing) so that you can make HTTP requests from a different domain than the one you use for your Flask application written in Python.

We will just add a kind of middleware to modify all the responses and add the headers that allow CORS in Flask.

Enable Cross Origin Resource Sharing in Flask

Just add the following code, with the @app.after_request annotation to indicate that we are modifying the response after the request:

"""
Enable CORS. Disable it if you don't need CORS
https://parzibyte.me/blog
"""
@app.after_request
def after_request(response):
    response.headers["Access-Control-Allow-Origin"] = "*" # <- You can change "*" for a domain for example "http://localhost"
    response.headers["Access-Control-Allow-Credentials"] = "true"
    response.headers["Access-Control-Allow-Methods"] = "POST, GET, OPTIONS, PUT, DELETE"
    response.headers["Access-Control-Allow-Headers"] = "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization"
    return response

The Access-Control-Allow-Origin indicates the domain from which the requests will be allowed. Credentials is useful in case you use sessions or cookies. Access-Control-Allow-Methods indicates which HTTP methods are valid for CORS.

Finally Access-Control-Allow-Headers indicates which headers will be accepted for CORS.

Remember that you are free to modify any value to adapt it to your needs.


I am available for hiring if you need help! I can help you with your project or homework feel free to contact me.
If you liked the post, show your appreciation by sharing it, or making a donation

parzibyte

Freelancer programmer ready to work with you. Web, mobile and desktop applications. PHP, Java, Go, Python, JavaScript, Kotlin and more :) https://parzibyte.me/

Entradas recientes

Receipt designer for thermal printers – Free and open source

In the last months I have been working on a ticket designer to print on…

11 months hace

JavaScript: store and read files with the Origin Private File System

In this post you will learn how to use the Origin Private File System with…

1 year hace

JavaScript: download file with fetch

In this post you will learn how to download a file in the background using…

1 year hace

SQLite3 with vanilla JavaScript and OPFS – Hello world

In this post I will show you how to use SQLite3 directly in the web…

1 year hace

Python Thermal Printing: A Comprehensive Guide for Printing on Thermal Printers

In this tutorial, we'll explore how to effortlessly print receipts, invoices, and tickets on a…

1 year hace

Image printing on Thermal printer

When printing receipts on thermal printers (ESC POS) sometimes it is needed to print images…

1 year hace

Esta web usa cookies.