Transferring information from a React Native user interface to an Express server

I'm currently learning React and working on a MERN stack project. I've been facing an issue with passing a variable from the frontend to the backend. Despite using console logs for debugging, I noticed that my request body is empty. I've dedicated several hours trying to pinpoint the mistake but so far, I haven't made any progress.

Below is the code snippet:

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;
        
        const user = await User.find({ email: email });
        console.log("Users for req: ", user);
    
        res.send(user);
      } catch (err) {
        console.log(err);
      }
    });

Answer №1

The problem lies in the HTTP method being used. Your route/API is set up as a GET call, which does not support sending a body with the request. To fix this, you can either change the method to POST or access the data using 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) => {

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Generate a unique identifier for the HTML content

Is there a more efficient way to assign unique id tags to certain words using vanilla javascript? For example: <p>All the king's horses ran away.</p> For instance, "All" would have the id "term1", "King's" would have "term2", and ...

Learning to Use jQuery to Send JSON Requests in Rails

I am attempting to send a JSON post request to a Rails 3 server. Here is the AJAX request I have set up: $.ajax({ type: 'POST',<br> contentType: "application/json",<br> url: url, ...

Testing for packet loss using JavaScript

Do you know if there is a method in JavaScript to determine packet loss from the client side using AJAX, XMLHttpRequest, or any other approach? Your assistance is greatly appreciated. ...

What is the process for obtaining the outcome of an ajax request?

After the request is complete, I want to run specific code. I'm unsure if this is the correct approach. Can you provide guidance on this? Thank you! Handling Ajax Requests function sendRequest(url, data, type) { return $.ajax({ url: ur ...

Ensure that your POST requests include only one file upload per request, as per MinIO express guidelines

After obtaining the information from a Minio presigned Post Policy to upload files (using Postman), I received the following response: View Image The Minio presigned Post Policy response is outlined below: { "formData": { "bucket&q ...

Tips for extracting parameters from a JSON String using JavaScript

When attempting to parse a JSON String, I am encountering an issue where the parsed value is coming up as undefined. You can view the code on this jsfiddle link. <input type="submit" onclick=testJSON() value="Test"/> <div i ...

Having difficulty implementing pagination functionality when web scraping using NodeJS

Currently, I am creating a script that scrapes data from public directories and saves it to a CSV file. However, I am encountering difficulties when trying to automate the pagination process. The source code I am using includes: const rp = require(' ...

Merging data from Angular RxJs Observable streams

I'm currently in the process of restructuring my Angular code to be more "reactive." One challenge I'm facing involves handling data returned from an Observable that retrieves account information into an object. Here's an example: { acc ...

jQuery - Issue arises when no radio button is selected

Currently, I am working with a group of radio buttons and need to implement validation that shows an error message if none of the buttons are checked. Is there a method to retrieve the combined value of all radio buttons at once, or will I have to indivi ...

Tips for launching and troubleshooting an AngularJS application within Eclipse

Looking to dive into Nodeclipse and get up and running with debugging an AngularJS application like the angular-phonecat example from Eclipse. Specifically, I want to utilize a Debug on Server launcher to kick off a server with my app and launch a web b ...

Can the Three.js Orbit Controls be customized to modify their appearance?

While I appreciate the orbit controls that come with Three.js, I am wondering if there is a way to customize them to follow the path of an ellipse (or technically an ellipsoid) instead of a circle. My main goal is to move the camera in an ellipse using th ...

Apply an opacity setting of 0.5 to the specific segment representing 30% of the scrollable div

I have a scrollable container for displaying messages. I would like to apply an opacity of 0.5 to the content in the top 30% of the container, as shown in this image: https://i.stack.imgur.com/NHlBN.png. However, when I tried using a background div with a ...

Exploring the concept of recursive method calls in TypeScript

I am trying to call the filterArr method inside the filterArr itself. Here is my current implementation: function filterArr(array, search) { var result = []; array.forEach((a)=> { var temp = [], o = {}, ...

ng-model fails to synchronize with HTML

When I click on ng-click, the model changes but the HTML remains the same... HTML <p>Reserved:<span>{{seatsInfo}}</span></p> <div ng-click="change()">change</div> JavaScript $scope.seatsInfo = 20; $scope.change = fu ...

JavaScript: Show Loading Screen until certain assets are fully loaded

Just a quick overview. I currently have a loading screen that appears before the website finishes loading for a specified time. What I'm looking to achieve is a method to check if certain elements are loaded and then remove the loading screen, rathe ...

What is the best method for extracting specific JSON response elements and appending them to an array?

I've been utilizing the Nomics cryptocurrency API in my project. Below is an example of the Axios call: axios.get(apiURL + apiKey + apiSpecs) .then(function (response) { // sort data by highest market cap console.log(response.data) }) Here' ...

Changing the text displayed after a checkbox is checked

I am currently working on creating a form that includes both checkboxes and text entry fields. The goal is to have related text appear next to each checkbox when it is checked. However, my current code does not seem to be functioning as expected: HTML: & ...

Choose the div element by its id with vanilla JavaScript instead of using the jQuery $ selector in order to utilize the RaphaelJS

Currently, I am utilizing the RaphaelJs' mousedown() method. However, I am encountering a problem as I wish to apply mousedown() on a div that is selected using the $(id) selector of JQuery. In this case, I prefer to use vanilla Js for performance rea ...

Using ASP.NET MVC to incorporate RenderAction with dynamic JavaScript parameters

Is there a way to pass a JavaScript variable into an MVC RenderAction parameter? @{Html.RenderAction("GeneratePlayersSelect", new { teamid = ??? ] });} I would greatly appreciate any assistance on this. Thank you in advance. ...

I'm having trouble connecting to the MongoDB Compass replicaset database. Direct Connection seems to be the only method that works

My attempt at connecting my replica set with MongoDB compass is failing because the application string isn't working correctly. I currently have 3 instances of MongoDB set up. https://i.sstatic.net/8UoMX.png mongoSet [direct: primary] test> rs.st ...