0

I am running my react app at port 3000 & express server at port 4000 , on the same local machine.

In my react app , using fetch api i am sending my registration form data to my express server at '/register' route-

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');
    }

}

And in my express server , i am doing a post method at '/register' route and storing the form data in my database -

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);
    })
})

In package.json filee for my react app , i added the proxy to localhost:4000(express server defined at port 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"
    ]
  }
}

And in my firefox console i am facing this error -

enter image description here enter image description here enter image description here

And in the browser under network tab i am getting this -

enter image description here

I am facing a 422 status error.I have been trying to solve this issue for the past 5 hours but after reading many solutions & articles i am not able to solve this issue of mine.I also checked similar questions on stackoverflow but the solution to them didnt worked.Basically , i am trying to send my registration form data from my react app to my express server by defining a proxy in the package.json file(of react app) , but i dont know why react is still considering it's own port 3000 instead of the server port 4000.Please help me solve this problem.Thanks a lot.

Bhavesh Damor
  • 61
  • 2
  • 14
  • 422 usually means a validation problem. Your request body might be wrong. What's in the response body? – Evert Apr 14 '21 at 18:55
  • @Evert i edited the code above , in my response body i am sending the registration form data filled by the user to the '/register' route in my express server.And in my server using req.body i am fetching all the user datas. – Bhavesh Damor Apr 15 '21 at 07:31
  • That's the request body. Share what your server is returned in the response body. – Evert Apr 15 '21 at 15:21
  • @Evert added the server code too,Thank you for your time – Bhavesh Damor Apr 15 '21 at 18:00
  • Try to share the response body. It's in your network tab – Evert Apr 15 '21 at 18:03
  • @Evert Added it too. – Bhavesh Damor Apr 15 '21 at 18:12
  • No you have not. Take some time to learn how to do this because I won't ask a 5th time. I'm expecting some kind of error message in the response body. – Evert Apr 15 '21 at 18:27
  • @Evert This is my first time working on something like this.And i am sort of new to these things as it's only been 2 months since i started developing so i dont know all about it.I can understand that it is frustrating for you to not getting what you asked for and i apologise for my incomprehension.But I am still not sure where ' the error message in the response body ' is present in my browser. – Bhavesh Damor Apr 15 '21 at 18:41
  • Well, you have a response tab in 2 of your screenshots. Take a look at that! – Evert Apr 15 '21 at 18:46
  • @Evert It was showing 'email doesnot exist' , I dont know how but i was able to store data in my db but on the webpage i was not able to get any alert messages nor any console messages which i defined.Unknowingly the proxy method was working.But as i have also used useHistory hook to redirect to my login page , i am not redirecting.Now researching on the error - `Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data` – Bhavesh Damor Apr 15 '21 at 19:26

1 Answers1

1

You can see the proxy is not working by the url localhost:3000/register. The proxy setting only works in development mode and that is not certain as well. You have two options:

Either write the whole url in your fetch requests or make a fetch interceptor to add the 'localhost:4000' before every API call.

P.S. And a third option: You can use axios instead of fetch if you don't want to write a custom fetch interceptor. Axios instances are pretty easy to do: https://medium.datadriveninvestor.com/axios-instance-interceptors-682868f0de2d

voxtool
  • 345
  • 4
  • 11
  • If i add the whole url then i am facing the cors error and i properly dont know how to work with cors npm. – Bhavesh Damor Apr 15 '21 at 18:15
  • 1
    Cors is very easy to set in express. You only need to install it using **npm install cors** and then const cors = require('cors') -> app.use(cors({origin: localhost:3000, credentials: true})) and that is it. Credentials is only needed if you use cookies as an aithentication. – voxtool Apr 15 '21 at 18:19
  • looks easy , i will give it a go. – Bhavesh Damor Apr 15 '21 at 18:21
  • 1
    Yeah on origin add the wholre url like a string, like this **app.use(cors({ origin: 'http://localhost:3000' , credentials : true}))** – voxtool Apr 15 '21 at 18:24
  • i am facing this error - `Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:4000/register. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘localhost:3000’).` – Bhavesh Damor Apr 15 '21 at 18:29
  • 1
    Add it with the http:// in front. The formatting removed it from my precvious comment. Alternatively if you DON'T use any authentication at the moment or you send a token with the response you can only do app.use(cors()); – voxtool Apr 15 '21 at 18:32
  • 1
    If you set a cookie you need to specify the option {credentials: true} in cors and on the front end you need to add credentials: 'include' to every fetch request, as I showed in my comment but if you send the JWT token as a response with res.send() or res.json() you don't need to do anything else. – voxtool Apr 15 '21 at 18:49
  • Thank you so much for your time man ,really appreciate it.I am able to store the data in my database.God bless you. – Bhavesh Damor Apr 15 '21 at 18:54
  • 1
    Glad to help. You can accept the answer if it helped you so the question can be set as complete. – voxtool Apr 15 '21 at 19:01
  • brother , now i am facing another issue – Bhavesh Damor Apr 15 '21 at 19:27
  • Yeah what it is? – voxtool Apr 15 '21 at 19:33
  • So , i am able to store the data in the db but in my frontend code i am checking for the data and alerting as well as console logging the message.Also redirecting the page to login page using useHistory hook but neither the messages are showing nor the page is redirecting.Also i am facing this error now `Uncaught (in promise) SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data` – Bhavesh Damor Apr 15 '21 at 19:36
  • Well that can be many things, it is best to open another question for this and provide all the needed code and screenshots of the errors if needed. – voxtool Apr 15 '21 at 19:39
  • yeah that seems professional.Thank you once again. – Bhavesh Damor Apr 15 '21 at 19:42