vue-resource可以在跨域时直接发送POST请求吗?

时间:2017-02-27 17:13:30

标签: ajax flask vue.js

我使用vue.js构建前端并在http://localhost:8080上使用npm run dev进行开发。

我使用flask来构建后端并在http://localhost:8081上运行它。

我还在Flask中为我的路线设置了跨域装饰器

def crossdomain(origin=None, methods=None, headers=None,
                max_age=21600, attach_to_all=True,
                automatic_options=True):
    if methods is not None:
        methods = ', '.join(sorted(x.upper() for x in methods))
    if headers is not None and not isinstance(headers, basestring):
        headers = ', '.join(x.upper() for x in headers)
    if not isinstance(origin, basestring):
        origin = ', '.join(origin)
    if isinstance(max_age, timedelta):
        max_age = max_age.total_seconds()

    def get_methods():
        if methods is not None:
            return methods

        options_resp = current_app.make_default_options_response()
        return options_resp.headers['allow']

    def decorator(f):
        def wrapped_function(*args, **kwargs):
            if automatic_options and request.method == 'OPTIONS':
                resp = current_app.make_default_options_response()
            else:
                resp = make_response(f(*args, **kwargs))
            if not attach_to_all and request.method != 'OPTIONS':
                return resp

            h = resp.headers

            h['Access-Control-Allow-Origin'] = origin
            h['Access-Control-Allow-Methods'] = get_methods()
            h['Access-Control-Max-Age'] = str(max_age)
            if headers is not None:
                h['Access-Control-Allow-Headers'] = headers
            return resp

        f.provide_automatic_options = False
        return update_wrapper(wrapped_function, f)
    return decorator

@app.route("/api", methods=['POST', 'OPTIONS'])
@crossdomain(origin="*")
def test():
    return "hello world"

然后我将POST vue-resource请求发送到后端:

this.$http.post("http://localhost:8081/api", "somedata").then({}, {})

毫不奇怪,浏览器发送OPTIONS请求。

所以我的问题是:

  1. 既然服务器端允许跨域,我可以直接POST发送vue-resource请求吗?
  2. 如果没有,我必须使用来自flask_cors的CORS吗?
  3. 有没有办法可以在8080端口上运行前端和后端,这可以防止出现跨域问题?

1 个答案:

答案 0 :(得分:0)

好吧,我还没有看到你所有的前端代码,但我想知道你是否设置了Vue.http.headers?

您可以在前端设置如下所示的公共标题:

Vue.http.headers.common['Access-Control-Allow-Origin'] = value;

更多信息: CORS issue with Vue.js