无法将请求从 React 前端发送到 Express 后端

问题描述 投票:0回答:1

我正在制作一个带有 REACT 前端和 EXPRESS 后端的待办事项应用程序

这是我的 App.jsx 代码

import { useEffect, useState } from 'react'
import LandingPage from './components/LandingPage.jsx'
import Dashboard from './components/Dashboard.jsx'
import Navbar from './components/Navbar.jsx'
import axios from 'axios';
import './App.css';

function App() {

  // State hooks
  const [user, setUser] = useState(false);
  const [sign, setSign] = useState("up");
  
  // Sign Up or Sign In
  const toggleSign = () => {
    setSign(sign === "up" ? "in" : "up");
  }

  // changingUser
  const changeUser = (newUser) => {
    console.log("User is changing");
    setUser(newUser);
  }
 
  // rendering main component
  const mainRender = (user) => {
    if(user.isAuthenticated) {
      return (<><Dashboard name={user.name} /></>);
    } else {
      return (<><LandingPage changeUser={changeUser} toggleSign={toggleSign} sign={sign} /></>);
    }
  }

 // getting dashboard response
 useEffect(() => {
    async () => {
      const response = await axios.get('/api/dashboard');
      setUser(response.data);
    }
  });

  // registering user
  useEffect(() => {
    console.log("User Changed");
    if(user) {
      async () => {
        const response = await axios.post('/api/register', user);
        console.log(response.data.registrationSuccessful);
        if(response.data.registrationSuccessful) {
          setUsernameChecks(false);
          toggleSign();
        } else {
          setUsernameChecks(true);
        }
      }
    }
  }, [user]);

  return (
    <>
      <Navbar />
      {mainRender(user)}
    </>
  )
}

export default App
 

这是我的index.js代码

//post register Route
app.post("/api/register", async (req, res) => {
    console.log("recieved post request");
    try {
        const result1 = await db.query("SELECT * FROM users WHERE username = $1", [req.body.username]);
        if(result1.rows.length === 0) {
            try {
                bcrypt.hash(req.body.password, saltRounds, async (err, hash) => {
                    if(err) {
                        console.error(`Error hashing passwrod: ${err}`)
                        res.json({registerationSuccessful: false, registerationMessage: err});
                    } else {
                        await db.query("INSERT INTO users (username, password, name) VALUES ($1, $2, $3)", [req.body.username, hash, req.body.name]);
                        res.json({registerationSuccessful: true});
                    }
                });
            } catch(err) {
                console.error(`Error executing insert query: ${err}`);
                res.json({registerationSuccessful: false, registerationMessage: err});
            }
        } else {
            res.json({registerationSuccessful: false, registerationMessage: "USER ALREADY EXITS!!!"});
        }
    } catch (err) {
        console.error(`Error executing search query: ${err}`);
        res.json({registerationSuccessful: false, registerationMessage: err});
    }
});

//get dashboard route

app.get("/api/dashboard", (req, res) => {
    console.log("recieved get dashboard request");
    res.json({...req.user, isAuthenticated: req.isAuthenticated()});
});

我已经通过 POSTMAN 检查过,我的 index.js 工作正常,用户正在使用 POSTMAN 注册并存储在数据库中。 在我的反应前端中,

useState({})
变量
user
使用函数
changeUser()
从表单组件正确设置。一旦我点击表单组件中的提交按钮,用户就会被设置,正如我在 chrome 开发工具中看到的那样。 console.logs 也在执行:
console.log("User is changing");
(来自changeUser()函数)
console.log("User changed");
(来自注册用户的useEffect钩子) 但请求尚未发送,我可以确认,因为在两种路由(GET 仪表板和 POST 寄存器)的情况下,index.js 文件中的 console.logs 都没有被执行。

以下是我的代理服务器的 vite.config.js 代码

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [react()],
  server: {
    proxy: {
      '/api': 'http://localhost:3000'
    }
  }
})

我没有收到任何错误,但 axios 请求也没有被执行。请帮忙

reactjs node.js express react-hooks axios
1个回答
0
投票

您的前端代码没有运行向后端发出请求的函数。我稍微更正了您的代码

useEffect
以使一切正常:

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

import Dashboard from './components/Dashboard.jsx';
import LandingPage from './components/LandingPage.jsx';
import Navbar from './components/Navbar.jsx';

import './App.css';

function App() {
    // State hooks
    const [user, setUser] = useState(false);
    const [sign, setSign] = useState('up');

    // Sign Up or Sign In
    const toggleSign = () => {
        setSign(sign === 'up' ? 'in' : 'up');
    };

    // changingUser
    const changeUser = (newUser) => {
        console.log('User is changing');
        setUser(newUser);
    };

    // rendering main component
    const mainRender = (user) => {
        if (user.isAuthenticated) {
            return (
                <>
                    <Dashboard name={user.name} />
                </>
            );
        } else {
            return (
                <>
                    <LandingPage changeUser={changeUser} toggleSign={toggleSign} sign={sign} />
                </>
            );
        }
    };

    // getting dashboard response
    useEffect(() => {
        const getDashboard = async () => {
            const response = await axios.get('/api/dashboard');
            setUser(response.data);
        };

        getDashboard();
    });

    // registering user
    useEffect(() => {
        console.log('User Changed');

        const registerUser = async () => {
            const response = await axios.post('/api/register', user);
            console.log(response.data.registrationSuccessful);
            if (response.data.registrationSuccessful) {
                setUsernameChecks(false);
                toggleSign();
            } else {
                setUsernameChecks(true);
            }
        };

        if (user) {
            registerUser();
        }
    }, [user]);

    return (
        <>
            <Navbar />
            {mainRender(user)}
        </>
    );
}

export default App;
© www.soinside.com 2019 - 2024. All rights reserved.