gpt4 book ai didi

javascript - Angular 前端和 Python 后端的 CORS 问题

转载 作者:行者123 更新时间:2023-11-28 08:10:13 26 4
gpt4 key购买 nike

我已经像这样设置了一个基于 Flask 的 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)

现在我正在对这个应用程序进行休息调用,该应用程序使用 Angular 容器中的末端 Angular 进行支持。

$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 问题。有人能做到这一点吗?需要帮助。

最佳答案

尝试将其添加到您的 Controller 中我之前也遇到过同样的问题

$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";

关于javascript - Angular 前端和 Python 后端的 CORS 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24299994/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com