[Python] When using Python Flask for the backend and Next.js for the frontend, if I am unable...

Discussão em 'Python' iniciado por Stack, Maio 18, 2025.

  1. Stack

    Stack Membro Participativo

    I got 404 This page could not be found error

    fetch('http://127.0.0.1:5000/api/users') this links display the output but it doesn't visible on the Page.

    this is users.tsx coding

    import React, { useEffect, useState } from 'react';

    interface User {
    id: number;
    username: string;
    address: string;
    }

    export default function UsersPage() {
    const [users, setUsers] = useState<User[]>([]);

    useEffect(() => {
    fetch('http://127.0.0.1:5000/api/users')
    .then(res => res.json())
    .then(data => setUsers(data))
    .catch(err => console.error('Fetch error:', err));
    }, []);

    return (
    <div className="min-h-screen p-8 bg-gray-100">
    <h1 className="text-3xl font-bold mb-6 text-center">User List</h1>
    <table className="w-full bg-white shadow-lg rounded-lg">
    <thead>
    <tr className="bg-gray-200">
    <th className="py-2 px-4">ID</th>
    <th className="py-2 px-4">Username</th>
    <th className="py-2 px-4">Address</th>
    </tr>
    </thead>
    <tbody>
    {users.map(user => (
    <tr key={user.id} className="border-t">
    <td className="py-2 px-4">{user.id}</td>
    <td className="py-2 px-4">{user.username}</td>
    <td className="py-2 px-4">{user.address}</td>
    </tr>
    ))}
    </tbody>
    </table>
    </div>
    );
    }



    app.py coding

    from flask import Flask, request, jsonify
    from flask_cors import CORS
    import mysql.connector
    import os
    from dotenv import load_dotenv

    load_dotenv()

    app = Flask(__name__)
    CORS(app)

    def get_connection():
    return mysql.connector.connect(
    host=os.getenv('DB_HOST'),
    port=os.getenv('DB_PORT'),
    user=os.getenv('DB_USER'),
    password=os.getenv('DB_PASS'),
    database=os.getenv('DB_NAME')
    )

    @app.route('/api/save', methods=['POST'])
    def save_data():
    username = request.form.get('username')
    address = request.form.get('Address')

    if not username or not address:
    return jsonify({"error": "Username and Address required"}), 400

    conn = get_connection()
    cursor = conn.cursor()
    cursor.execute(
    "INSERT INTO user_queries (username, address) VALUES (%s, %s)",
    (username, address)
    )
    conn.commit()
    cursor.close()
    conn.close()

    return jsonify({"message": "Data saved successfully!"}), 200


    @app.route('/api/users', methods=['GET'])
    def get_users():
    conn = get_connection()
    cursor = conn.cursor(dictionary=True)
    cursor.execute("SELECT * FROM user_queries") # your table
    users = cursor.fetchall()
    cursor.close()
    conn.close()
    return jsonify(users), 200

    if __name__ == '__main__':
    app.run(debug=True)

    Continue reading...

Compartilhe esta Página