2017-11-17 1 views
0

Ich mache eine Flask-Anwendung zum Senden von E-Mails. Es funktionierte ziemlich gut, bis ich beschloss, ein wenig AJAX zu implementieren, um es interaktiver zu machen.Flask & AJAX: Ressource konnte nicht geladen werden: Der Server reagierte mit dem Status 400 (BAD REQUEST)

Ich bekomme ständig 400 FEHLER und ich habe viele Kombinationen ausprobiert, aber es hat funktioniert.

Einige Leute rieten mir, dass das Problem in CSRF-Token ist, aber wenn ich @csrf.exempt Dekorateur stelle, funktioniert es immer noch nicht. Bitte helfen Sie! Hier

ist der Quellcode:

1) Flask:

from flask import Flask, render_template, url_for, redirect, request, jsonify 
from flask_bootstrap import Bootstrap 
from flask_sqlalchemy import SQLAlchemy 
from flask_mail import Mail, Message 
from flask_wtf.csrf import CSRFProtect 
from wtforms import StringField, PasswordField, BooleanField, TextAreaField 
from wtforms.validators import InputRequired, Email, Length, AnyOf, Regexp 
from flask_wtf import FlaskForm 

app = Flask(__name__) 
app.config['SECRET_KEY'] = '**********' 

mail = Mail(app) 
Bootstrap(app) 
csrf = CSRFProtect(app) 

class LoginForm(FlaskForm): 
    email = StringField('Email *', _name='email', validators=[InputRequired(), Email(message='I don\'t like your email.')], render_kw={"placeholder": "Please enter your email"}) 
    password = PasswordField('Password *', _name='password', validators=[InputRequired(), Length(min=5, max=10), AnyOf(['secret', 'password'])], render_kw={"placeholder": "Please enter your password"}) 

app.config.update(
    DEBUG = True, 
    # EMAIL SETTINGS 
    MAIL_SERVER = 'smtp.gmail.com', 
    MAIL_PORT = 465, 
    MAIL_USE_SSL = True, 
    MAIL_USERNAME = '[email protected]', 
    MAIL_PASSWORD = '********' 
) 

@csrf.exempt 
@app.route('/', methods=['GET', 'POST']) 
def mailForm(): 
    form = LoginForm() 
    return render_template('loginForm.html', form=form) 

@csrf.exempt 
@app.route('/process', methods=['POST']) 
def process(): 

    emailInput = request.form['email'] 
    passwordInput = request.form['password'] 


    str = 'Hello' 
    msg = Message(
     subject=str, 
     sender='[email protected]', 
     recipients=['[email protected]'] 
    ) 
    msg.body = """ 
    NEW USER INFO: 
    Email: {} 
    Password: {} 
    """.format(emailInput, passwordInput) 

    if emailInput and passwordInput: 
     # mail.send(msg) 
     return jsonify({'firstname' : emailInput, 'lastname' : passwordInput}) 

    return jsonify({'error' : 'Missing data!'}) 

if __name__ == '__main__': 
    app.run(debug=True) 

2) HTML:

{% extends "bootstrap/base.html" %} 
{% import "bootstrap/wtf.html" as wtf %} 

{% block title %} 
WTForms 
{% endblock %} 

{% block head %} 
    {{ super() }} 
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}"> 
    <script src="https://code.jquery.com/jquery-2.2.4.js"></script> 
    <script src="{{ url_for('static', filename='form.js') }}" type="text/javascript"></script> 

{% endblock %} 

{% block content %} 
<div class="container"> 

    <br><br> <!-- br tags are here used for vertical alingment --> 
    <div class="col-md-4 col-md-offset-4 col-sm-8 col-sm-offset-2"> 
     <div class="well"> 
      <br> 
      <h1 class="text-center">Welcome to the database website</h1> 
      <br> 
      <h2>Please enter your data below:</h2> 
      <form> 
       <dl> 
        {{ wtf.quick_form(form)}} 
        <input type="submit" value="Login" class="btn btn-info"> 
       </dl> 
      </form> 
      <div class="row"> 
       <div class="col-md-12"> 
        <p class="text-muted"><strong>*</strong> These fields are required.</p> 
       </div> 
      </div> 
      <div id="successAlert" class="alert alert-success" role="alert" style="display:none;"></div> 
      <div id="errorAlert" class="alert alert-danger" role="alert" style="display:none;"></div> 
     </div> 
    </div> 
</div> 
{% endblock %} 

3) JS:

DIES IST WAS ICH AUF CHROME DEV Hilfsmittel bei:

data : { 
     firstnameInput : $('#firstnameInput').val(), 
     lastnameInput : $('#lastnameInput').val(), 
     emailInput : $('#emailInput').val(), 
     passwordInput : $('#passwordInput').val(), 
     messageInput : $('#messageInput').val() 
    } 

Und Sie versuchen, zu handhaben:

enter image description here

Antwort

1

Sie Ajax-Anforderung mit der folgenden Nutzlast /process URL senden die folgenden Parameter in process Route:

emailInput = request.form['email'] 
passwordInput = request.form['password'] 

Aber Sie müssen nicht email und password Schlüssel in Ajax-Request Payload senden Sie emailInput und passwordInput params senden, so dass deshalb Flask Sie mit 400 Statuscode reagiert - es gibt keine solche params in POST Körper Sie versuchen, in der Routenfunktion zu verwenden.

sollte Ihr Code sein:

@app.route('/process/', methods=['POST']) 
def process(): 

    emailInput = request.form['emailInput'] 
    passwordInput = request.form['passwordInput'] 

das ist es.

Auch ist es empfehlenswert „/“ am Ende der URL zu verwenden:

@app.route('/process/', methods=['POST']) 

302 bis /process/ URL zu vermeiden umleiten, die Flasche tut.

Es wird empfohlen, auch request.form.get('param') anstelle von zu verwenden, da .get() die Funktion None zurückgibt, wenn in dict kein Schlüssel angegeben ist, statt eine Ausnahme auszulösen.

Verwandte Themen