How to Enable CORS in Flask: A Step-by-Step Guide

Linda Hamilton
Release: 2024-10-28 09:22:30
Original
853 people have browsed it

How to Enable CORS in Flask: A Step-by-Step Guide

How to Enable CORS in Flask

Cross-Origin Resource Sharing (CORS) allows web applications to make requests to servers on different origins (domains, ports, or protocols) than the one on which they were originally loaded. When a client makes a cross-origin request, the server can decide whether to allow the request or not by setting the 'Access-Control-Allow-Origin' header.

To enable CORS in Flask, you can use the 'flask-cors' extension. This extension provides a simple and consistent way to configure CORS for your Flask application.

To install 'flask-cors', use the following command:

pip install -U flask-cors
Copy after login

Once you have installed 'flask-cors', you can configure it for your Flask application by adding the following code to your application:

<code class="python">from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'

@app.route("/")
@cross_origin()
def helloWorld():
  return "Hello, cross-origin-world!"</code>
Copy after login

The 'CORS_HEADERS' configuration option specifies the allowed request headers. In this example, it allows the 'Content-Type' header, which is the default header used when sending a POST request.

The '@cross_origin()' decorator specifies that the function should allow cross-origin requests. It can be used on individual routes or on the entire application.

By following these steps, you can enable CORS in your Flask application and allow cross-origin requests from other domains.

The above is the detailed content of How to Enable CORS in Flask: A Step-by-Step Guide. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template