我的快速服务器的代理服务器在我的 React 应用程序中不起作用

问题描述

我在同一台本地机器上在端口 3000 和 Express 服务器的端口 4000 上运行我的 react 应用程序。

在我的 react 应用程序中,使用 fetch api 我将我的注册表单数据发送到我的快速服务器中的“/register”路由-

const response = await fetch('/register',{
        method: 'POST',headers : {
            "Content-Type" : "application/json"
        },body: JSON.stringify({
            name: username,email : useremail,phone : userphone,work : userwork,password: userpassword,cpassword : usercpassword
        })
    });

    const data = await response.json();

    if(data.status === 422 || !data){
        window.alert("Invalid registration");
        console.log("Invalid registration");
    }else{
        window.alert("registration successful");
        console.log("registration successful");

       //using useHistory hook
        history.push('/login');
    }

}

在我的快速服务器中,我在“/register”路由上执行 post 方法并将表单数据存储在我的数据库中 -

router.post('/register',(req,res)=>{
    
    const {name,email,phone,work,password,cpassword} = req.body;

    //we are checking if any of the inputs are empty or not
    if(!name || !email || !phone || !work || !password || !cpassword){
        return res.status(422).send('Please Fill All The Fields');
    }

    //we are observing if a user already registered or not by checking it's email
    User.findOne({email : email})
            .then((userExist) =>{
                    if(userExist){
                        return res.status(422).send('Email already exists');
                    }else if(password !== cpassword){
                        return res.status(422).send('Passwords are not matching');
                    }

                    //if the email dont exist,that means the user is new and we will store it's data in the DB
                    const user = new User({
                        name : name,email : email,phone : phone,work : work,password : password,cpassword : cpassword,});

                //saved the stored data in the DB
            user.save()
            .then(()=>{
                res.status(201).send('User registered Successfully')
            })
            .catch((err)=>{
                res.status(500).send(err);
            })

    }).catch((err)=>{
        console.log(err);
    })
})

在我的 react 应用程序的 package.json 文件中,我将代理添加到 localhost:4000(在端口 4000 定义的快速服务器)-

{
  "name": "frontend","version": "0.1.0","private": true,"proxy" : "http://localhost:4000","dependencies": {
    "@testing-library/jest-dom": "^5.11.10","@testing-library/react": "^11.2.6","@testing-library/user-event": "^12.8.3","bootstrap": "^5.0.0-beta3","react": "^17.0.2","react-dom": "^17.0.2","react-router-dom": "^5.2.0","react-scripts": "4.0.3","web-vitals": "^1.1.1"
  },"scripts": {
    "start": "react-scripts start","build": "react-scripts build","test": "react-scripts test","eject": "react-scripts eject"
  },"eslintConfig": {
    "extends": [
      "react-app","react-app/jest"
    ]
  },"browserslist": {
    "production": [
      ">0.2%","not dead","not op_mini all"
    ],"development": [
      "last 1 chrome version","last 1 firefox version","last 1 safari version"
    ]
  }
}

在我的 Firefox 控制台中,我遇到了这个错误 -

enter image description here

enter image description here

enter image description here

在网络选项卡下的浏览器中,我得到了这个 -

enter image description here

我正面临 422 状态错误。过去 5 小时我一直在尝试解决这个问题,但在阅读了许多解决方案和文章后,我无法解决我的这个问题。我还在 stackoverflow 上检查了类似的问题,但是他们的解决方案没有奏效。基本上,我试图通过在 package.json 文件(react app)中定义一个代理,将我的注册表数据从我的 react 应用程序发送到我的 express 服务器,但我不知道为什么 react 仍然存在考虑到它是自己的3000端口而不是服务器端口4000。请帮我解决这个问题。非常感谢。

解决方法

您可以通过 url localhost:3000/register 看到代理不起作用。代理设置仅适用于开发模式,这也不确定。您有两个选择:

要么在你的 fetch 请求中写下整个 url,要么在每次 API 调用之前制作一个 fetch 拦截器来添加 'localhost:4000'。

附言还有第三种选择:如果您不想编写自定义 fetch 拦截器,则可以使用 axios 代替 fetch。 Axios 实例很容易实现:{{3}}