启用CORS的Flask restful api无法用于远程ajax调用

时间:2015-03-07 04:23:25

标签: python ajax flask cors flask-restful

我有一个烧瓶应用程序,我有一个安静的api,我试图通过远程服务器调用。

init 文件: -

from flask.ext import restful
from flask.ext.cors import CORS

app = create_app(__name__)
app.config['CORS_HEADERS'] = 'Content-Type'
cors = CORS(app, resorces={r'/d/<string:d_name>': {"origins": '*'}})
api=restful.Api(app)
api.add_resource(g_Api, '/g/<string:g_id>')
api.add_resource(d_Api, '/d/<string:d_name>')

现在是d_Api类: -

from flask import Flask, render_template, g
from flask.ext.restful import reqparse, abort, Api, Resource
    def abort_if_not_exist(d_name):
      return d_name

    class d_Api(Resource):
      def __init__(self):
        self.d=d

      def get(self, d_name):
        val=abort_if_not_exist(d_name)
        return val

这可以从同一个localhost服务器返回正确的结果。在localhost上运行的服务器对api进行ajax调用,

$.ajax({
                                    async: false,
                                    type: 'GET',
                                    url: 'http://localhost:8080/d/'+d_name,
                  success: function(data) {
                                        alert(data);
                                        }
});

当从remotehost调用时不返回任何响应,而是在Firefox中我得到跨源请求被阻止:同源策略不允许读取远程资源d。这可以通过将资源移动到同一域或启用CORS来解决。

m not sure how else to configure CORS for this api endpoint. I使用python 2.6和&#39; flask-cors&#39;。

我发现了这个区别:当我尝试从本地主机点击api时 - 2015-03-09 11:40:35 - Flask-Cors:385 - INFO - CORS request from Origin:xyz-ld2.abc.biz:8080, setting Access-Control-Allow-Origin:* 当我尝试从远程主机点击api时:2015-03-09 11:47:15 - Flask-Cors:385 - INFO - CORS request from Origin:None, setting Access-Control-Allow-Origin:*

3 个答案:

答案 0 :(得分:1)

问题在于资源定义,您只能使用正则表达式来获取资源 你需要这样的东西或任何其他有效的正则表达式:

cors = CORS(app, resorces={r'/d/*': {"origins": '*'}})

答案 1 :(得分:0)

确定。问题是我正在使用

$.ajax({
                                    async: false,
                                    type: 'GET',
                                    url: 'http://localhost:8080/d/'+d_name,
                  success: function(data) {
                                        alert(data);
                                        }
});

Url as localhost,这不是正确的方法。您应始终使用托管内容的IP或VIP或域地址。 例如:url : 'http:// xyz .com:8080/d'+d_name'将起作用。对于https://使用

url:"//xyz. com/d/d_name" i.e. without the protocol.

答案 2 :(得分:0)

问题在于您的代码中的此语句:

cors = CORS(app, resorces={r'/d/<string:d_name>': {"origins": '*'}})

来自文档:http://flask-cors.corydolphin.com/en/latest/api.html?highlight=origin#flask_cors.cross_origin

flask_cors.cross_origin(*args, **kwargs) The origin, or list of origins to allow requests from. The origin(s) may be regular expressions, case-sensitive strings, or else an asterisk

在这里,您需要提供RegEx;像:

cors = CORS(app, resorces={r'/d/*': {"origins": '*'}})

这将在以CORS

开头的所有路线上启用/d/

希望这有帮助!