我使用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
请求。
所以我的问题是:
POST
发送vue-resource
请求吗?8080
端口上运行前端和后端,这可以防止出现跨域问题?答案 0 :(得分:0)
好吧,我还没有看到你所有的前端代码,但我想知道你是否设置了Vue.http.headers?
您可以在前端设置如下所示的公共标题:
Vue.http.headers.common['Access-Control-Allow-Origin'] = value;
更多信息: CORS issue with Vue.js