【问题标题】:Request always returns 400 when sent from application (flask_corse)从应用程序发送请求时始终返回 400 (flask_corse)
【发布时间】:2018-06-12 05:47:54
【问题描述】:

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

您可以在下面看到我的应用程序的初始化:

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),但实际请求仍然失败。

感谢任何提示或建议。

【问题讨论】:

  • 伙计,我不认为发布你的 ip 是个好主意......
  • 这不是真实的ip :)。我改变了它。不过谢谢。
  • 您尝试过 Content-Type application/json 吗?因为您发送的是正文中的 JSON 数据,而不是 urlencoded 数据。
  • 是的,我也试过了。不幸的是,它也不起作用..

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


【解决方案1】:

尝试改变这一行:

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

到:

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

【讨论】:

  • 感谢您的提示。不幸的是,它不起作用。我认为问题与 corse 调用有关。
【解决方案2】:

当这条线失败 email = request.form['email'] 然后烧瓶发送 400 错误请求。 检查请求正文是 json 还是使用 request.isjson() 的任何其他类型,如果不是,则使用 data = request.getjson() 将数据转换为 json

【讨论】:

  • 不幸的是它不起作用。请求没有函数 isjson() 或 getjson()。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-11
  • 2019-09-04
  • 2020-10-15
  • 1970-01-01
  • 1970-01-01
  • 2021-07-10
相关资源
最近更新 更多