Flask cors error

I am kind of new to Python, but I have had the same issue working with Node apps. I am making a pretty standard jQuery AJAX request to my local Python sever: init: function(callback) { ...

I am kind of new to Python, but I have had the same issue working with Node apps. I am making a pretty standard jQuery AJAX request to my local Python sever:

init: function(callback) {
            var token = _config.get_token();

            $.ajax({
                    url: 'http://localhost:5000/api/ia/v1/user_likes',
                    type: 'POST',
                    contentType: 'application/json',
                    datatype: 'json',
                    data: token
                })
                .done(function(data) {
                    callback(data);
                })
                .fail(function(err) {
                    callback(err);
                });

            callback(token);
        }

I can confirm that the variable token is confirming like this:

Object {access_token: "791415154.2c0a5f7.4d707361de394512a29682f9cb2d2846", campaign_id: "102"}

But I am getting this error from my javascript console:

XMLHttpRequest cannot load http://localhost:5000/api/ia/v1/user_likes. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://s3.amazonaws.com' is therefore not allowed access. The response had HTTP status code 500.

I have found that when I am building Node apps that this is a cors error. The page that I am running the jQuery AJAX request from is http. Here are the parts of my Python code that I believe I am configuring incorrectly:

from flask import Flask, request, redirect
from flask.ext.cors import CORS, cross_origin

app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'application/json'

And the route:

@app.route("/api/ia/v1/user_likes", methods=['POST', 'OPTIONS'])
def user_likes():
    validate = validate_request(request.data)

    return 'something'

My Python error is also returning an error because the request is never making it to this line of code:

def validate_request(object_from_user):
    load_object = json.loads(object_from_user)

I can fix that later. Anyway, does anyone have any suggestions for Cors configurations for Python?

Arunkumar Dharuman

In this video, I’ll show how to enable Flask-CORS for Flask based API projects. Explains and code three different options available to configure CORS for your projects.

Python;
https://www.python.org

Flask;
https://flask.palletsprojects.com

Flask-CORS;
https://flask-cors.readthedocs.io

Top comments (0)

For further actions, you may consider blocking this person and/or reporting abuse

Read next


leandcesar profile image

Qual ORM usar no seu próximo projeto Python?

Leandro César — Jan 13


kboskin profile image

Building Web Applications with React and Python

Kostiantyn Boskin — Jan 2


bascodes profile image

This Week In Python

Bas codes — Jan 13


holger profile image

Azure SDK for Python: Retrieve Virtual Machine Image Details

holger — Jan 13

Once suspended, arundhaj will not be able to comment or publish posts until their suspension is removed.

Once unsuspended, arundhaj will be able to comment and publish posts again.

Once unpublished, all posts by arundhaj will become hidden and only accessible to themselves.

If arundhaj is not suspended, they can still re-publish their posts from their dashboard.

Note:

Once unpublished, this post will become invisible to the public and only accessible to Arunkumar Dharuman.

They can still re-publish the post if they are not suspended.

Thanks for keeping DEV Community 👩‍💻👨‍💻 safe. Here is what you can do to flag arundhaj:

Make all posts by arundhaj less visible

arundhaj consistently posts content that violates DEV Community 👩‍💻👨‍💻’s
code of conduct because it is harassing, offensive or spammy.

Unflagging arundhaj will restore default visibility to their posts.

Flask-CORS

Build Status Latest Version
Supported Python versions

License

A Flask extension for handling Cross Origin Resource Sharing (CORS), making cross-origin AJAX possible.

This package has a simple philosophy: when you want to enable CORS, you wish to enable it for all use cases on a domain.
This means no mucking around with different allowed headers, methods, etc.

By default, submission of cookies across domains is disabled due to the security implications.
Please see the documentation for how to enable credential’ed requests, and please make sure you add some sort of CSRF protection before doing so!

Installation

Install the extension with using pip, or easy_install.

$ pip install -U flask-cors

Usage

This package exposes a Flask extension which by default enables CORS support on all routes, for all origins and methods.
It allows parameterization of all CORS headers on a per-resource level.
The package also contains a decorator, for those who prefer this approach.

Simple Usage

In the simplest case, initialize the Flask-Cors extension with default arguments in order to allow CORS for all domains on all routes.
See the full list of options in the documentation.

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route("/")
def helloWorld():
  return "Hello, cross-origin-world!"

Resource specific CORS

Alternatively, you can specify CORS options on a resource and origin level of granularity by passing a dictionary as the resources option, mapping paths to a set of options.
See the full list of options in the documentation.

app = Flask(__name__)
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})

@app.route("/api/v1/users")
def list_users():
  return "user example"

Route specific CORS via decorator

This extension also exposes a simple decorator to decorate flask routes with.
Simply add @cross_origin() below a call to Flask’s @app.route(..) to allow CORS on a given route.
See the full list of options in the decorator documentation.

@app.route("/")
@cross_origin()
def helloWorld():
  return "Hello, cross-origin-world!"

Documentation

For a full list of options, please see the full documentation

Troubleshooting

If things aren’t working as you expect, enable logging to help understand what is going on under the hood, and why.

logging.getLogger('flask_cors').level = logging.DEBUG

Tests

A simple set of tests is included in test/.
To run, install nose, and simply invoke nosetests or python setup.py test to exercise the tests.

Contributing

Questions, comments or improvements?
Please create an issue on Github, tweet at @corydolphin or send me an email.
I do my best to include every contribution proposed in any way that I can.

Credits

This Flask extension is based upon the Decorator for the HTTP Access Control written by Armin Ronacher.

Понравилась статья? Поделить с друзьями:
  • Firefox cors error
  • Flask 404 ошибка
  • Flashtool ошибка brom error 0x1
  • Flashtool ошибка 5007
  • Flashtool ошибка 3152