Home > OS >  Send data from React Native front end to Express back end
Send data from React Native front end to Express back end

Time:12-30

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

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

CodePudding user response:

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) => {
  • Related