Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Send data from React Native front end to Express back end

I’m new to React and building a MERN stack. I’m having issues passing a variable from my front end to my back end. I’ve tried using console logs to debug and I can see that my request body is coming up blank. I’ve spent hours trying to figure out what I’m doing wrong but I haven’t had any breakthrough yet.

Please see my code below.

User Frontend Hook

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const fetchUser = (dispatch) => {
  return async () => {
    const email = await AsyncStorage.getItem("email");
    console.log("async email:", email);
    try {
      console.log("sending email:", email);
      const userInfo = await trackerApi.get("/users", {email});
      dispatch({ type: "fetch_users", payload: userInfo.data });
    } catch (err) {
      console.log(err);
    }
  };
};

Express/Axios Backend

router.get("/users", async (req, res) => {
 
     console.log("Request Body:", req.body);
      try {
        const { email } = req.body;
        // console.log("Email for req: ", email);
    
        const user = await User.find({ email: email });
        console.log("Users for req: ", user);
    
        res.send(user);
      } catch (err) {
        console.log(err);
      }
    });

>Solution :

The issue is related to the HTTP method, your route/API is GET call and get method does not have the body, either update to post or use req.query.

Client

const userInfo = await trackerApi.post("/users", {email});
// OR
const userInfo = await trackerApi.post("/users", { data: {email});

Server

router.post("/users", async (req, res) => {
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading