我已经设置了一个基于烧瓶的api后端。
from datetime import timedelta
from flask import Flask, make_response, request, current_app, jsonify
from functools import update_wrapper
app = Flask(__name__)
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('/', methods=['GET', 'POST'])
@crossdomain(origin='*')
def landing():
if request.method == 'POST':
data = request.data
return 'God saved the post'
else:
return jsonify(i_am_a='cross domain resource!')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8080, debug=True)
现在我正在使用角度容器中的角度来自这个应用程序来支持这个应用程序。
$http.get('http://127.0.0.1:8080')
.success(function(gdata) {
$scope.gdata = gdata;
});
var pdata = {'message': 'i am post data'};
$http.post('http://127.0.0.1:8080', pdata)
.success(function(pdata) {
$scope.pdata = pdata;
});
我的GET成功了,但是当有POST时我遇到了CORS问题。有人得到这个工作,需要帮助。
答案 0 :(得分:0)
尝试将此添加到您的控制器 我之前遇到过同样的问题
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
答案 1 :(得分:0)
您可以在 Python 后端使用 Flask-CORS,这将解决 CORS 问题