NodeJS 无法从Fast API获取数据

hiz5n14c  于 2023-08-04  发布在  Node.js
关注(0)|答案(1)|浏览(119)

伙计们,我目前正在开发一个学生考勤应用程序,使用React,Node和Express with Fast API,我使用Get Method从API的getAllUser中获取数据,并将其保存在下面的表中,它完美地工作了

和代码

import axios from "axios";

  export default function Users() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

      useEffect(() => {
        async function fetchUsers() {
            try {
                const response = await axios.get('http://localhost:3001/getAllUsers');
                setUsers(response.data);
                setLoading(false);
            } catch (error) {
                setError("Failed to fetch data");
                setLoading(false);
            }
        }

        fetchUsers();
    }, []);  

    if (loading) {
        return <div>Loading...</div>;
    }

    if (error) {
        return <div>Error: {error}</div>;
    }

return (
        <div>
            <h1>Users</h1>
            <div className="user-container">
                <table className="user-table">
                    <thead>
                    <tr>
                        <th>FIRST NAME</th>
                        <th>LAST NAME</th>
                        <th>PHONE NUMBER</th>
                        <th>EMAIL</th>
                        <th>USER TYPE</th>
                    </tr>
                    </thead>
                    <tbody>
                    {users.map((user) => (
                        <tr key={user.id}>
                            <td>{user.firstName}</td>
                            <td>{user.lastName}</td>
                            <td>{user.phoneNumber}</td>
                            <td>{user.email}</td>
                            <td>{user.userType}</td>
                        </tr>
                    ))}
                    </tbody>
                </table>
            </div>
        </div>
    );
}

字符串
但当我试图获取数据时,添加电子邮件地址时,它不会显示任何错误,它不会显示以下代码的输出,我提供了不工作的部分

import React, {useState, useEffect} from "react";
import axios from "axios";

export default function Users() {
    const [users, setUsers] = useState([]);
    const [email, setEmail] = useState("");

    const handleSearchClick = async () => {
        try {
            const response = await axios.get(`http://localhost:3001/getUser?email=${email}`);
            setUsers(response.data);
            setLoading(false);
        } catch (error) {
            setError("Failed to fetch data");
            setLoading(false);
        }
    }

    if (loading) {
        return <div>Loading...</div>;
    }

    if (error) {
        return <div>Error: {error}</div>;
    }

    return (
        <div>
            <h1>Users</h1>
            <div className="user-container">
                <form className="search-user">
                    <input
                        type="text"
                        placeholder="email address"
                        value={email}
                        onChange={(e) => setEmail(e.target.value)}
                    />
                    <button className="search-user-btn" onClick={handleSearchClick}>
                        Search
                    </button>
                </form>

                <table className="user-table">
                    <thead>
                    <tr>
                        <th>FIRST NAME</th>
                        <th>LAST NAME</th>
                        <th>PHONE NUMBER</th>
                        <th>EMAIL</th>
                        <th>USER TYPE</th>
                    </tr>
                    </thead>
                    <tbody>
                    {users.map((user) => (
                        <tr key={user.id}>
                            <td>{user.firstName}</td>
                            <td>{user.lastName}</td>
                            <td>{user.phoneNumber}</td>
                            <td>{user.email}</td>
                            <td>{user.userType}</td>
                        </tr>
                    ))}
                    </tbody>
                </table>
            </div>
        </div>
    );
}


下面我提供了server.js代码

const express = require("express");
const axios = require("axios");
const cors = require("cors");
const {response} = require("express");

const app = express();
const port = 3001;
const FASTAPI_URL = 'http://174.138.23.76:8000';

app.use(express.json());
app.use(cors({origin: "http://localhost:3000", credentials: true,
    methods: ['GET', 'PUT', 'POST', 'DELETE', 'OPTIONS'],
}));

// app.use((req, res, next) => {
//     res.header("Access-Control-Allow-Origin", "*");
//     res.header(
//         "Access-Control-Allow-Headers",
//         "Origin, X-Requested-With, Content-Type, Accept"
//     );
//     next();
// });

app.post("/createUser", async (req, res) => {
    try {
        const formData = req.body;
        // Make a POST request to the FastAPI backend with 'no-cors' mode
        const response = await axios.post(`${FASTAPI_URL}/createUser`, formData);
        console.log("User created:", response.data);
        // Perform any necessary actions after successful user creation
        res.json(response.data);
    } catch (error) {
        console.error("Error creating user:", error);
        // Handle error condition
        res.status(500).json({ error: "Failed to create user" });
    }
});

app.post("/user/login", (req, res) => {
    const {email, password} = req.body;

    // Make a POST request to the FastAPI backend for login with 'no-cors' mode
    axios
        .post("http://174.138.23.76:8000/user/login", {email, password})
        .then((response) => {
            console.log("Login successful:", response.data);
            // Perform any necessary actions after successful login
            res.status(200).json(response.data);
        })
        .catch((error) => {
            console.error("Error logging in:", error);
            // Handle error condition
            res.status(500).json({error: "Failed to log in"});
        });
});

app.get("/getAllUsers", async (req, res) => {
    try {
        const url = `${FASTAPI_URL}/getAllUsers`;
        const response = await axios.get(url);
        res.json(response.data);
    } catch (error) {
        res.status(500).json({error: "Failed to fetch data"});
    }
});

app.get("/getUser", async (req, res) => {
    try {
        const { email } = req.query; // Destructure the email from req.query directly
        const url = `${FASTAPI_URL}/getUser?email=${email}`;
        const response = await axios.get(url);
        res.json(response.data);
    } catch (error) {
        res.status(500).json({ error: "Failed to fetch data" });
    }
});

app.delete("/deleteUser", async (req, res) => {
    const { email } = req.query;
    try {
        const url = `${FASTAPI_URL}/deleteUser?email=${email}`;
        const response = await axios.delete(url);
        res.json(response.data);
    } catch (error) {
        res.status(500).json({ error: "Failed to delete user" });
    }
});

app.post("/updateUser", (req, res) => {
    const updateData = req.body;
    axios
        .post('http://174.138.23.76:8000/updateUser', updateData)
        .then((response) => {
            console.log("User Updated:", response.data);

            res.status(200).json(response.data);
        })
        .catch((error) => {
            console.error("Error Updating user:", error);

            res.status(500).json({error: "Failed to Update user"})
        })
})

app.listen(port, () => {
    console.log(`Server listening at http://localhost:${port}`);
})


请帮我解决这个问题

olqngx59

olqngx591#

编辑客户端

const response = await axios.get(`http://localhost:3001/getUser/${email}`);

字符串
在服务器端添加

app.get('/user/:email', function (req, res) {
   try {
        const { email } = req.params.email; 
        const url = `${FASTAPI_URL}/getUser/${email}`; // main change
        const response = await axios.get(url);
        res.json(response.data);
   } catch (error) {
       res.status(500).json({ error: "Failed to fetch data" });
   }
})

相关问题