Problems with flask and javascript

the idea is when you click in teh button of an actuador it will send a mesage to the microcontroler to acivate 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 mesage will be sent and the error disappears

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật