Home > database >  The browser (or proxy) sent a request that this server could not understand
The browser (or proxy) sent a request that this server could not understand

Time:12-12

I'm getting an error when I try to post the data using Postman to my python, flask and MySQL backend server.

Postman Request: enter image description here

Error Message:

enter image description here

My code:

@app.route('/product', methods=['POST'])
def insert_product():
    request_payload = json.loads(request.form['data'])
    product_id = products_dao.insert_new_product(connection, request_payload)
    response = jsonify({
        'product_id': product_id
    })
    response.headers.add('Access-Control-Allow-Origin', '*')
    return response

insert_new_product function

def insert_new_product(connection, product):
    cursor = connection.cursor()
    query=("insert into products (name, uom_id, price_per_unit) VALUES (%s, %s, %s)")
    data = (product['product_name'],product['uom_id'], product['price_per_unit'])
    cursor.execute(query, data)
    connection.commit()
    return cursor.lastrowid

CodePudding user response:

Because you send data in the format content-type: application/json, you can't use request.form['data'] to parse it, instead you should use request.json to parse it.

@app.route('/product', methods=['POST'])
def insert_product():
    request_payload = request.json
    product_id = products_dao.insert_new_product(connection, request_payload)
    response = jsonify({
        'product_id': product_id
    })
    response.headers.add('Access-Control-Allow-Origin', '*')
    return response
  • Related