how to send data from a form to my database through a post method

58 Views Asked by At

This is my html where i have the form

enter image description here

this is my api:

@app.route('/productos', methods=['POST'])
def registrar_producto():
    try:
        cursor = conexion.connection.cursor()
        sql = """INSERT INTO productos (idproductos, productos_name, productos_descripcion, productos_precio) 
        VALUES ('{0}', '{1}', '{2}', {3})""".format(request.json['idproductos'], request.json['productos_name'], request.json['productos_descripcion'], request.json['productos_precio'])
        cursor.execute(sql)
        conexion.connection.commit() # confirma la accion de agregar
        return jsonify({"Mensaje":"Producto registrado correctamente"})
    except Exception as ex:
        return jsonify({"Error": 'Este producto ya existe'})

this is my vue app:

async nuevoProducto() {
            try {
                const response = await fetch('http://127.0.0.1:5000/productos', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(this.nuevoProducto)
                });
                if (response.ok) {
                    console.log('Producto agregado con éxito.');
                    this.obtenerProductos();
                    this.nuevoProducto = {
                        idproductos: '',
                        productos_name: '',
                        productos_descripcion: '',
                        productos_precio: 0,
                    };
                } else {
                    console.error('Error al agregar el producto:', response.statusText);
                }
            } catch (error) {
                console.error('Error al agregar el producto:', error);
            }
        }
    },

using Thunder Client it works perfectly but if i try to add this data through the form it doesnt

enter image description here

i expect the data to be sent to the db using the form

0

There are 0 best solutions below