从应用程序发送请求时总是返回400(flask_corse)

时间:2018-01-02 14:02:13

标签: python python-3.x flask flask-cors

我有一个后端是在flask和flask_restful中实现的,并且有许多不同的路由。我的前端正在另一个来源上运行,这意味着我使用了flask_curse以允许我的前端向我的后端发送请求。

Bellow你可以看到我的应用程序的初始化:

app = Flask(__name__)
app.register_blueprint(check_routes_page)
CORS(app, supports_credentials=True)

以下是我从前端拨打的路线:

@check_routes_page.route(API_URL +API_VERSION +'check/email', methods=['POST'])
def check_email():
    email = request.form['email']
    user = User.query.filter(User.email == email).first()
    if user:
        return jsonify({'success':True}), 200
    else:
        return jsonify({'success': False}), 404

当我使用Postman发送请求时,一切都很完美。然而,当我从我的应用程序发送请求时,我总是回到400.我也改变了内容类型而没有任何成功。

以下是我从申请表发送的请求。

checkMailAddress(email: string): boolean {

        let requestUrl = 'http://X/application/api/V0.1/check/email';
        let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
        let body = JSON.parse('{"email":"' + email + '"}');
        let options = new RequestOptions({ headers: headers });
        let respo: any
        let us = this.http.post(requestUrl, body, options)
            .map((response) => response.json())
            .subscribe(
            function(response) {
                console.log("Success Response:" + response);
                respo = response;

            },
            function(error) {
                console.log("Error happened" + error);
            },
            function() {
                console.log("the subscription is completed");
                console.log(respo.status);
            }
            );
        return true;
    }

当我发送内容类型为Json的请求时,客户端首先发送一个选项请求(返回代码200),但仍然失败并显示实际请求。

我很感谢任何提示或建议。

2 个答案:

答案 0 :(得分:0)

尝试更改此行:

user = User.query.filter(User.email == email).first()

为:

user = User.query.filter(email=email).first()

答案 1 :(得分:0)

当此行失败email = request.form['email']时,随后发送400个错误请求。 使用request.isjson()检查请求正文是否为json或任何其他类型,如果没有,则使用data = request.getjson()将数据转换为json