Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

javascript - Python Flask Cors Issue

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

After I tried others suggestions and answers. Here's what I use, which works.

Steps:

  1. pip install flask flask-cors

  2. Copy and paste this in app.py file

Code

from flask import Flask, jsonify
from flask_cors import CORS, cross_origin

app = Flask(__name__)
CORS(app, support_credentials=True)

@app.route("/login")
@cross_origin(supports_credentials=True)
def login():
  return jsonify({'success': 'ok'})

if __name__ == "__main__":
  app.run(host='0.0.0.0', port=8000, debug=True)
  1. python app.py

Note: be sure in your client's ajax configuration has the following:

$.ajaxSetup({
    type: "POST",
    data: {},
    dataType: 'json',
    xhrFields: {
       withCredentials: true
    },
    crossDomain: true,
    contentType: 'application/json; charset=utf-8'
});

If one wonders, support_credentials=True just means it sends cookies along the payload back and forth.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...