Problems with flask and javascript

the idea is when you click in the button of an actuador , it will send a message to the microcontroller to activate or deactivate a switch. The thing is that when I click on the actuador to send the MQTT message the following error appears:

Enviando comando al actuador 3: 1
1:954 Body being sent: {"mensaje":"1"}
1:955 1
1:956 
        
        
       POST http://127.0.0.1:5001/enviar_comando_actuador/3 400 (BAD REQUEST)
toggleSwitch @ 1:956
onclick @ 1:370
1:963 Response status: 400
1:979 Error al enviar comando al actuador: Error: HTTP status 400
    at 1:965:19

I have this html code:

{% for actuador in actuadores %}
  <div class="elemento">
    {% if actuador.tipo == 'switch' %}
    <button class="switch-button" id="switch_{{ actuador.id }}" 
    data-actuador-id="{{ actuador.id }}" 
    data-state="{{ actuador.estado_actual }}" 
    onclick="toggleSwitch(this)"
    style="background-color: {{ 'green' if actuador.estado_actual == '1' else 'red' }}">
        <span>{{ actuador.nombre }}</span><br>
        <span>{{ actuador.tipo }}</span><br>
        <span>{{ actuador.ubicacion }}</span>
    </button>

    
    
    {% elif actuador.tipo == 'altavoz' %}
    <button class="switch-button" id="switch_{{ actuador.id }}" data-actuador-id="{{ actuador.id }}" data-state="" onclick="">
        <span>{{ actuador.nombre }}</span><br>
        <span>{{ actuador.tipo }}</span><br>
        <span>{{ actuador.ubicacion }}</span>
    </button>
    
    {% endif %}
    <div class="menu-button" onclick="showMenu({{ actuador.id }})">...</div>
  </div>
{% else %}
  <p>No hay actuadores agregados. Por favor, agregue uno.</p>
{% endfor %}

The Javascript:

function toggleSwitch(buttonElement) {
    const actuadorId = buttonElement.dataset.actuadorId;
    let currentState = buttonElement.dataset.state;
    const newState = currentState === '1' ? '0' : '1';

    console.log(`Enviando comando al actuador ${actuadorId}: ${newState}`);
    console.log(`Body being sent:`, JSON.stringify({ mensaje: newState }));
    console.log(newState)
    fetch(`/enviar_comando_actuador/${actuadorId}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ mensaje: newState })
        
    })
    .then(response => {
        console.log('Response status:', response.status);
        if (!response.ok) {
            throw new Error(`HTTP status ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        console.log('Respuesta del servidor:', data);
        if (data.success) {
            buttonElement.dataset.state = newState;
            buttonElement.style.backgroundColor = newState === '1' ? 'green' : 'red';
        } else {
            console.error('Error al procesar el comando:', data.message);
        }
    })
    .catch(error => {
        console.error('Error al enviar comando al actuador:', error);
    });
}

This is the flask route:

@main.route('/enviar_comando_actuador/<int:actuador_id>', methods=['POST'])
@login_required
def enviar_comando_actuador(actuador_id):
    if not request.is_json:
        print("Error: No JSON received")
        return jsonify({'success': False, 'message': 'Expected JSON content'}), 400

    data = request.get_json()
    comando = data.get('mensaje')
    print(f"Received JSON: {data}")  # Imprimir los datos JSON recibidos
    print(f"Received command for actuator {actuador_id}: {comando}")

    if comando not in ['0', '1']:
        print("Error: Invalid command value")
        return jsonify({'success': False, 'message': 'Invalid command value'}), 400

    try:
        actuador = Actuador.query.get(actuador_id)  # Use get() instead of get_or_404()
        if not actuador:
            print(f"Actuator with ID {actuador_id} not found")
            return jsonify({'success': False, 'message': 'Actuator not found'}), 404  # Return 404 for missing actuator
        print(f"Command {comando} will be sent to actuator {actuador_id}")
        # Simular el envío de comando al hardware aquí si es necesario
        return jsonify({'success': True, 'message': 'Comando enviado correctamente.', 'estado': comando})
    except Exception as e:
        print(f"Error while processing command: {str(e)}")
        return jsonify({'success': False, 'message': 'Error al enviar comando.', 'error': str(e)}), 500

I expect that when I click the button the MQTT message will be sent and the error disappears