1

I know this question has been asked earlier but none of the solutions are working for me

Complete error log:

  1. Shown on client side
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. Shown on the server side network tab
Proxy error: Could not proxy request /contact from localhost:3000 to http://localhost:5000/ (ECONNRESET).
  1. Shown in console
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 client side

  "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 server side

  "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"
  }
}

server side files

auth.js (main router file aka server.js)

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

router.post("/contact", authenticate, 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,email,phone,msg);
        await userExists.save();
        res.status(201).json({ message: "Message sent" });
      }
    }
  } catch (error) {
    console.log(error);
  }
});

userschema.js (model file for the database, only added the required code here instead of full code)

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

client side file - 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, email, phone, msg } = userData;

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

    const data = await res.json();

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

Palx
  • 57
  • 5

1 Answers1

-1

I solved it by just putting / after http://localhost:500 correct way is

"proxy": "http://localhost:5000/"
Ali Faiz
  • 212
  • 2
  • 9
  • Use axios instead of fetch for api call in fetch this is common error. if you still want to use fetch then in your api you 1st need to convert data in JSON.stringify before send to client side and then in client side first parse data to json and then use it. but axios is preferable because you don't need to to convert to JSON and then parse it again – Ali Faiz Jul 19 '21 at 08:02