[Python] How to enable CORS in flask

Discussão em 'Python' iniciado por Stack, Abril 21, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to make a cross origin request using jquery but it keeps being reject with the message


    XMLHttpRequest cannot load http://... No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ... is therefore not allowed access.
    ​

    I am using flask, heroku, and jquery

    the client code looks like this:

    $(document).ready(function() {
    $('#submit_contact').click(function(e){
    e.preventDefault();
    $.ajax({
    type: 'POST',
    url: 'http://...',
    // data: [
    // { name: "name", value: $('name').val()},
    // { name: "email", value: $('email').val() },
    // { name: "phone", value: $('phone').val()},
    // { name: "description", value: $('desc').val()}
    //
    // ],
    data:"name=3&email=3&phone=3&description=3",
    crossDomain:true,
    success: function(msg) {
    alert(msg);
    }
    });
    });
    });


    on the heroku side i am using flask and it is like this

    from flask import Flask,request
    from flask.ext.mandrill import Mandrill
    try:
    from flask.ext.cors import CORS # The typical way to import flask-cors
    except ImportError:
    # Path hack allows examples to be run without installation.
    import os
    parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    os.sys.path.insert(0, parentdir)

    from flask.ext.cors import CORS
    app = Flask(__name__)

    app.config['MANDRILL_API_KEY'] = '...'
    app.config['MANDRILL_DEFAULT_FROM']= '...'
    app.config['QOLD_SUPPORT_EMAIL']='...'
    app.config['CORS_HEADERS'] = 'Content-Type'

    mandrill = Mandrill(app)
    cors = CORS(app)

    @app.route('/email/',methods=['POST'])
    def hello_world():
    name=request.form['name']
    email=request.form['email']
    phone=request.form['phone']
    description=request.form['description']

    mandrill.send_email(
    from_email=email,
    from_name=name,
    to=[{'email': app.config['QOLD_SUPPORT_EMAIL']}],
    text="Phone="+phone+"\n\n"+description
    )

    return '200 OK'

    if __name__ == '__main__':
    app.run()

    Continue reading...

Compartilhe esta Página