Tips for executing a successful POST request from a react-native application to an express.js server connected to a mySQL database

Following a series of tutorials, I set up an express.js backend with a MySQL database. The tutorials can be found here and here. After testing all the routes using Postman, everything was working correctly.

Next, I attempted a simple Get request using React Native to fetch data from a table in the database:

<Button title='Test MySQL Connection' 
   onPress = {()=>{
     fetch('http://my_laptop_IP:3000/users')
     .then(response => response.json())
     .then(users => alert(users))}}
 />

This worked seamlessly.

However, when trying to insert a row into the table using a Post request, it failed:

<Button title='Test MySQL Connection' 
   onPress={()=>{    
     fetch('http://my_laptop_IP:3000/users', {
       method: 'POST',
       headers: {       
         Accept: 'application/x-www-form-urlencoded',
         'Content-Type': 'application/x-www-form-urlencoded',
       },
       body: JSON.stringify({
         first_name:'Cell',
         last_name: 'First_form',
       })
     })
     .then((response) => response.json())
     .then((response) => {
        alert(response);
      })
     .catch((error) => alert('Error ' + error));
    }}
 />

An error occurred as shown in this screenshot for the express backend: https://i.sstatic.net/J4wPI.png

The issue is displayed on my virtual device emulator here:

https://i.sstatic.net/rgYNq.png

I attempted changing the header part of the fetch request like this:

headers: {
   Accept: 'application/json',
   'Content-Type': 'application/json',
},

Unfortunately, this did not resolve the problem.

Answer №1

When sending JSON as the request body, you can use the following code snippet:

fetch("http://localhost:3000/users", {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        first_name: "Cell",
        last_name: "First_form"
      })
    })
      .then(response => response.json())
      .then(response => {
        console.log(response)
      })
      .catch(error => alert("Error " + error))

In addition, you may need to include the cors module in your server.js file:

var express = require("express");
var cors = require('cors');


app = express(),

port = process.env.PORT || 3000,
bodyParser = require("body-parser"),
controller = require("./controller");

app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var routes = require("./routes");
routes(app);

app.listen(port);
console.log("Learn Node JS With Kiddy, RESTful API server started on: " + port);

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

Avoid causing the newline character to display

var i = 'Hello \n World' console.log(i) /* Output: Hello World */ /* Desired output: Hello \n world */ var j = 'javscr\u0012ipt' console.log(j) /* Output: javscr ipt */ /* Desired output: javscr\u0012ipt */ ...

Having issues with ng-src and images not loading in the application

Is there a way to dynamically change the image source using ng-src? I've been attempting to switch the image file source based on an onclick event using the code below, but it's not working as expected. <html ng-app="ui.bootstrap.demo"> ...

Testing the path in a hurry - req.param

Is there a way to test an express route like app.get('/myapp/:parameter')? I'm trying to figure out how to use jest to verify that no parameter is passed. In my .ts file, I have an error set up to return a 400 if no parameter is passed, but ...

As I embark on building my web application using next.js, I begin by importing firebase from the "firebase" package. Unfortunately, a particular error unexpectedly surfaces in the terminal

I am currently developing a next.js web application and I have decided to utilize firebase for both database management and authentication. However, when attempting to import firebase in a specific file, I encountered the following error: Error - ./firebas ...

Determine the time left and check the speed of file uploads using ajax with jquery or javascript

Here is a snippet of code using jQuery.ajax to handle file uploads with progress tracking functionality. The function updates the DOM elements with information about bytes uploaded, total bytes, and percentage completed. However, I am looking for addition ...

When using the mui joy library, obtaining the input value upon submission may result in the retrieval of an "unidentified" response

Struggling to fetch user input for 2FA authentication using the mui JoyUI library. Attempted using e.target and searching for input value with no success. Clearly missing something in the documentation. Also gave 'useRef' a shot, but the code sni ...

Strategies for simplifying this extensive if/else block

My current if/else statement in React Native is functional but seems verbose. I am curious to know how other developers would optimize and shorten it. I feel like my code represents a beginner's approach, and I welcome suggestions on how to improve i ...

Creating a design utilizing HTML columns with a set height and the ability to scroll horizontally

For my android project, I have a requirement to display a view (WebView) that dynamically loads content. The content will consist of <div class="content-item"> tags that are added by JavaScript to <div class="content-holder"> after the page has ...

Clicking on the current component should trigger the removal of CSS classes on its sibling components in React/JSX

Currently, I am working on creating a navigation bar using React. This navigation bar consists of multiple navigation items. The requirement is that when a user clicks on a particular navigation item, the class 'active' should be applied to that ...

How to implement a form in PHP that doesn't refresh the page upon submission

I am having an issue with this ajax code. I know it works, but for some reason it's not submitting. <script type="text/javascript"> $(function(){ $('input[type=submit]').click(function(){ $.ajax({ type: "POST", ...

Using Django's template filters within a JavaScript script to manipulate an object's attribute

I am facing an issue where django's template filters are not working inside a js script when applied to an object's attribute. When I use the following code, it results in a js SyntaxError: <script> {{ obj.geometry.geojson | safe }} & ...

No data returned by MySqlCommand

I am facing an issue with my database where I have added a row using MySql query browser for testing. Strangely, this row is visible in PhpMyAdmin or MySql query browser, but when I try to access this table within my program, it shows that there are no row ...

404 error message generated by an Express route

I am encountering a 404 error on the express route of my node app. While it functions correctly locally, upon deployment to the production server, it begins returning the 404 error (please note that I have updated the AJAX URL to match the one on the produ ...

Route Angular 4 application static resources to a /PORT directory rather than the primary domain

Our Angular 4 application is integrated within a Node + Express app and started like a typical node app, such as: node index.js On a local machine, the Angular app is served from the /client directory: app.use(express.static(__dirname + "/client")); Onc ...

Getting React Developer Tools to Function with Webpack

I recently followed a tutorial on how to expose React as a global variable in Webpack using the Expose module. Despite installing the Expose module and adding the appropriate loader configuration in the webpack.config.js file, I am still unable to access R ...

Randomizing the JSON loop on every page refresh

Having a JSON file containing various data items (as an example) that I am utilizing with handlebars.js to generate templates. The challenge lies in displaying 15 stories (each within their own div) on page load while shuffling their positions upon each r ...

Challenges Encountered with jQuery/AJAX Form Processing

I am currently facing an issue with two files in my project. The main file, index.php, contains JavaScript code within the head section. Here is the snippet of JavaScript: <script src="http://code.jquery.com/jquery-latest.min.js" type= ...

Access to data retrieval was restricted by CORS policies on my Node.js/Express REST API server

I am currently running a localhost node/express server that is designed to accept any post request with a body and then return the same body along with a message. To enable Cross-Origin Resource Sharing (CORS), I have integrated the cors node package into ...

Utilize range slider to refine dataset

I have implemented a jquery datatable along with the range.slider plugin. My goal is to apply the range slider to filter out data in the last column. In my attempt, I am using search.push to accomplish this filtering process. Below is an example of my i ...

Encountered an issue while attempting to retrieve the access token from Azure using JavaScript, as the response data could

Seeking an Access token for my registered application on Azure, I decided to write some code to interact with the REST API. Here is the code snippet: <html> <head> <title>Test</title> <script src="https://ajax.google ...