3

我想在 127.0.0.1 的主干应用程序和 127.0.0.1:5000 的 Flask 服务器之间进行跨域请求。在我切换到 Backbone 之前,我有一个 Ember.js 应用程序,我遇到了同样的问题。但是我通过在我的 Flask 应用程序中添加它来让它工作:

@app.after_request
def after_request(data):
    response = make_response(data)
    response.headers['Content-Type'] = 'application/json'
    response.headers['Access-Control-Allow-Origin'] = 'http://localhost'
    return response

并以这种方式配置 Ember RESTAdapter

adapter: DS.RESTAdapter.create({ 
    url : 'http://127.0.0.1:5000',
    // In order to allow cross domain requests

    ajax: function(url, type, hash) {
       jQuery.ajax(url)
    }
  })
});

但这不适用于我的 Backbone 应用程序。

XMLHttpRequest无法加载http://127.0.0.1:5000/files。请求头域Content-Type是不允许的Access-Control-Allow-Headers

我想我必须在客户端更改一些设置。但我不知道是什么。我该怎么做才能进行跨域请求?

4

3 回答 3

3

这对我有用。

http://flask-cors.readthedocs.org/en/latest/

$ pip install -U flask-cors

from flask import Flask
from flask.ext.cors import CORS, cross_origin
app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'

@app.route("/")
@cross_origin()
def helloWorld():
  return "Hello, cross-origin-world!"
于 2014-10-16T03:05:17.633 回答
2

我通过添加使其工作

response.headers['Access-Control-Allow-Headers'] = "Origin, X-Requested-With,Content-Type, Accept"after_request()方法。

于 2013-05-03T08:34:02.660 回答
0

对于开发,您可以:

或者只是设置Access-Control-Allow-Origin*

于 2013-05-01T16:03:05.347 回答