MERN 堆栈中的代理错误:无法将请求 /contact 从 localhost:3000 代理到 http://localhost:5000

问题描述

我知道之前有人问过这个问题,但没有一个解决方案适合我

完整的错误日志:

  1. 显示在客户端
Proxy error: Could not proxy request /contact from localhost:3000 to http://localhost:5000/.
See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNRESET).
  1. 显示在服务器端网络选项卡上
Proxy error: Could not proxy request /contact from localhost:3000 to http://localhost:5000/ (ECONNRESET).
  1. 显示在控制台中
POST http://localhost:3000/contact 500 (Internal Server Error)
Uncaught (in promise) SyntaxError: Unexpected token P in JSON at position 0

The solutions tried

Package.json 客户端

  "name": "client","version": "0.1.0","private": true,"proxy": "http://localhost:5000","dependencies": {
    "@testing-library/jest-dom": "^5.14.1","@testing-library/react": "^11.2.7","@testing-library/user-event": "^12.8.3","framer-motion": "^4.1.17","react": "^17.0.2","react-dom": "^17.0.2","react-router-dom": "^5.2.0","react-scripts": "4.0.3","web-vitals": "^1.1.2"
  },}

package.json 服务器端

  "name": "server","version": "1.0.0","description": "","main": "index.js","scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },"author": "","license": "ISC","dependencies": {
    "bcryptjs": "^2.4.3","cookie-parser": "^1.4.5","dotenv": "^10.0.0","express": "^4.17.1","http-proxy-middleware": "^2.0.1","jsonwebtoken": "^8.5.1","mongoose": "^5.13.2"
  }
}

服务器端文件

auth.js(主路由器文件又名 server.js)

router.get("/getdata",authenticate,(req,res) => {
  res.send(req.rootUser);
});

router.post("/contact",async (req,res) => {
  console.log("in auth.js");
  try {
    const { name,email,phone,msg } = req.body;

    if (!name || !email || !phone || !msg) {
      console.log("fill all fields");
      return res.json({ error: "Fill all fields" });
    }

    //req.userID define in authenticate
    else {
      const userExists = await User.findOne({ _id: req.userId });

      if (userExists) {
        const userContact = await userExists.addMessage(name,msg);
        await userExists.save();
        res.status(201).json({ message: "Message sent" });
      }
    }
  } catch (error) {
    console.log(error);
  }
});

userschema.js(数据库的模型文件,这里只添加了需要的代码而不是完整代码

userSchema.methods.addMessage = async function (name,msg) {
  try {
    this.messages = this.messages.concat({
      name,msg,});
    await this.save();
    return this.messages;
  } catch (error) {
    console.log(error);
  }
};

客户端文件 - about.js


const Contact = () => {
  const [userData,setUserData] = useState({name: "",email: "",phone: "",msg: "",});

  const getuserData = async () => {
    try {
      const res = await fetch("/getdata",{
        method: "GET",headers: {
          "Content-Type": "application/json",},});

      const data = await res.json();

      setUserData({
        ...userData,name: data.name,email: data.email,phone: data.phone,});

      if (!res.status === 200) {
        const error = new Error(res.error);
        throw error;
      }
    } catch (error) {
      console.log(error);
    }
  };

  useEffect(() => {
    getuserData();
  },[]);

  const handleInput = (e) => {
    const key = e.target.name;
    const value = e.target.value;
    setUserData({ ...userData,[key]: value });
  };

  const sendMessage = async (e) => {
    console.log("in func");
    e.preventDefault();
    const { name,msg } = userData;

    const res = await fetch("/contact",{
      method: "POST",headers: {
        "Content-Type": "application/json",body: JSON.stringify({
        name,}),});

    const data = await res.json();

    if (!data) {
      console.log("msg from contact page not sent");
    } else {
      alert("Message Sent!");
      setUserData({ ...userData,msg: "" });
    }
  };

解决方法

我通过将 / 放在 http://localhost:500 之后解决了这个问题 正确的做法是

"proxy": "http://localhost:5000/"