错误:浏览器(或代理)发送了该服务器无法理解的请求

时间:2020-03-30 02:33:31

标签: python php html server

所以我在这段代码上遇到了麻烦,并且遇到了这个错误

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>The browser (or proxy) sent a request that this server could not understand.</p>

因此,检查所有内容后,我认为HTML文件在此处

 $("#button_confirm_transaction").click(function() {
                $.ajax({
                    url: document.getElementById("node_url").value + "/transactions/new",
                    type: "POST",
                    header: {'Access-Control-Allow-Origin':'*'},
                    dataType: 'json',
                    data: $('#confirmation_transaction_form').serialize(),
                    success: function(response) {

                        //reset both forms
                        $("#transaction_form")[0].reset();
                        $("#confirmation_transaction_form")[0].reset();

                        //clean text boxes
                        $('#sender_public_key').val('');
                        $('#sender_private_key').val('');
                        $('#recipient_public_key').val('');
                        $('#amount').val('');

                        $('#basic_modal').modal('hide');
                        $('#success_transaction_modal').modal('show');
                    },
                    error: function(error) {
                        console.log(error);
                    }
                })
            });

或在python代码本身中


from collections import OrderedDict
from time import time
from flask import Flask, jsonify, request, render_template
from flask_cors import CORS


class Blockchain:

    def __init__(self):
        self.transactions = []
        self.chain = []
        # Create genesis block
        self.create_block(0, '00')

    def create_block(self, nonce, previous_hash):
        """
        Add a block of transactions to the blockchain
        """
        block = {'block_number': len(self.chain) + 1,
                 'timestamp': time(),
                 'transactions': self.transactions,
                 'nonce': nonce,
                 'previous_hash': previous_hash}

        # Reset the current list of transactions
        self.transactions = []
        self.chain.append(block)

    def submit_transaction(self, sender_public_key, recipient_public_key, signature, amount):
        """
        Add a transaction to transactions array if the signature verified
        """
        # TODO: mining reward
        # TODO: signature validation
        transaction = OrderedDict({
            'sender_public_key': sender_public_key,
            'recipient_public_key': recipient_public_key,
            'signature': signature,
            'amount': amount
        })
        signature_verification = True
        if signature_verification:
            self.transactions.append(transaction)
            return len(self.chain) + 1
        else:
            return False


blockchain = Blockchain()


app = Flask(__name__)
CORS(app)




@app.route('/transactions/new', methods=['POST'])
def new_transaction():
    values = request.form
    # TODO: Check required fields
    transaction_result = blockchain.submit_transaction(values['confirmation_sender_public_key'],
                                                       values['confirmation_recipient_public_key'],
                                                       values['transaction_signature'], values['confirmation_amount'])

    if not transaction_result:
        response = {'message': 'Invalid Transaction!'}
        return jsonify(response), 406
    else:
        response = {'message': 'Transaction will be added to Block' + str(transaction_result)}
        return jsonify(response), 201


if __name__ == '__main__':
    from argparse import ArgumentParser

    parser = ArgumentParser()
    parser.add_argument('-p', '--port', default=5001, type=int, help='port to listen on')
    args = parser.parse_args()
    port = args.port

    app.run(host='127.0.0.1', port=port)

所以我知道那是错误:

127.0.0.1--[29 / Mar / 2020 22:26:48]“ POST / transactions / new HTTP / 1.1” 400-

从PyCharm控制台日志

有什么想法吗?我是python编程的新手,我一直在寻求将其修复2天

提前谢谢

1 个答案:

答案 0 :(得分:0)

因此,经过数小时试图弄清楚发生了什么事情,我注意到它在python代码末尾缺少debug=True

if __name__ == '__main__':
    from argparse import ArgumentParser

    parser = ArgumentParser()
    parser.add_argument('-p', '--port', default=5001, type=int, help='port to listen on')
    args = parser.parse_args()
    port = args.port

    app.run(host='127.0.0.1', port=port, debug=True)