Post 400 (BAD REQUEST)

2019-08-24 20:34发布

问题:

I'm attempting to submit my form, but it continually fails as there's something wrong with the POST. I'm unsure where/what exactly is causing the server to not process the request whether it's related to syntax, request routing, etc. I've also commented out every line related to file uploads, as well as comment out the if (validated) statement. There are no errors in the console as a result of this, but the form submission still fails. I'd appreciate any help/direction thanks.

I get this error message when I submit the form:

POST http://127.0.0.1:5051/register/ 400 (BAD REQUEST)

views.py

@blueprint.route("register/", methods=['GET', 'POST'])
def register():
    """Renders register page."""
    form = RegisterForm()
    if request.method == 'POST':
        if not form.validate_on_submit():
            return render_template('main/register.html', page_title="Service Registration",
                                   form=form, form_success=False, media_types=current_app.config["ACCEPTED_"
                                                          "MEDIA_TYPE"])
        ticket, err = create_ticket2(customer_id, organization + "\n" + venue_name + "\n" + street + "\n" + country + "\n" + teamviewquestion + "\n" + teamviewerid + "\n" + deviations + "\n" + deviationsnotes + "\n" + displaydirector + "\n" + composer + "\n" + decryptor + "\n" + motionrocket + "\n" + othersoftware,
                                     location=location)
        if err:
            return render_template('main/register.html', page_title="Service Registration",
                                   form=form, form_success=False, message=err, media_types=current_app.config["ACCEPTED_"
                                                          "MEDIA_TYPE"])
        else:
            success_msg = "Error"
                .format(ticket.get('id'))
            return render_template('main/register.html', page_title="Service Registration",
                                   form=form, form_success=True, message=success_msg, media_types=current_app.config["ACCEPTED_"
                                                          "MEDIA_TYPE"])
    return render_template('main/register.html', page_title="Service Registration",
                           form=form, media_types=current_app.config["ACCEPTED_"
                                                          "MEDIA_TYPE"])
    """Handles file upload POSTs."""
    first_name = request.form.get("first_name")
    last_name = request.form.get("last_name")
    name = request.form.get("first_name") + " " + request.form.get("last_name")
    email = request.form.get("email")
    filename = request.form.get("filename")
    file_type = request.form.get("file_type")
    if filename == '':
        response = make_response("No selected file")
        return response, 400
    if check_file_type(file_type):
        filename = clean_filename(filename)
        filename = secure_filename(filename)
        filename = unique_filename(filename)
        response = generate_presigned_post(filename, file_type)
        # CREATE DB REFERENCE
        url = "http://nevcodocs.s3.amazonaws.com/Uploads/{}".format(filename)
        instance = CustomerFileUpload.query.filter_by(url=url).first()
        if not instance:
            instance = CustomerFileUpload(url=url, email=email, name=name)
            db.session.add(instance)
            db.session.commit()
        else:
            instance.update(created_at=datetime.utcnow())
        return response, 200

js (ticket submission function)

$('#ticket-form').submit(function(event) {
            if (validated) {
                $('#filename').val($('#upload').val());
                $.ajax({
                    type: 'POST',
                    url: '/register/',
                    data: $('#ticket-form').serialize()
                }).done(function(data) {
                    var formData = new FormData();
                    for (var key in data.data) {
                        formData.append(key, data.data[key]);
                    }
                    formData.append('file', $('#upload').prop('files')[0]);
                    formData.append('csrf_token', '{{ csrf_token }}');
                    var req = new XMLHttpRequest();
                    req.onload = function() {
                        showSpinner(false);
                        $('#ticket-form').removeClass("support-form-show");
                        $('#ticket-form').addClass("support-form-hide");
                    };
                    req.onerror = function() {
                        showSpinner(false);
                        $('#ticket-form-failed').removeClass("support-form-hide");
                        $('#ticket-form-failed').addClass("support-form-show");
                    };
                    req.open('POST', '/register/');
                    req.send(formData);
                }).fail(function(err) {
                    showSpinner(false);
                    $('#ticket-form-failed').removeClass("support-form-hide");
                    $('#ticket-form-failed').addClass("support-form-show");
                });
            } else {
                showSpinner(false);
                enableSubmit(true);
            }
        });

回答1:

Usually, bad request means that you're trying to fetch data from request object using invalid keys. So you need to make sure that your POST request body (that was sent by javascript) contains all keys which you're using as arguments of request.form.get() method: first_name, last_name, etc...