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.