skip to Main Content

I’ve set up a node.js server with app.post and app.get and I want to post the data from the values of my form which the user fills in to insert in the database, in phpmyadmin. I use Express, body-parser, mysql for my node server. Now I use the fetch in my Registration class where I believe that the error comes from. The error is this: TypeError: Network request failed.

I use Android mobile which is connected to my pc through cable. What i’ve checked/tried:

  1. Fetch url is http (not https)
  2. I use my ip4 address (ipconfig > Wireless LAN adapter Wi-Fi > IPv4 address).(not localhost)
  3. I’ve tested the url in Postman. This works, with Postman I can POST and GET the data with the same URL. Only difference is in Postman I use localhost instead of my IPv4 address (ipconfig > Wireless LAN adapter Wi-Fi > IPv4 address).
  4. I’ve added header Content-Type: application/json. (see fetch code)
  5. Added android:usesCleartextTraffic=”true”> to my AndroidManifest.xml (Accepts clear traffic, such as HTTP)
  6. I’ve made this project in RN version 0.60.4 and also 0.59.8, came to same error, only the project I reproduced in 0.59.8, this fetch seems to work fluently with Postman, which it didn’t with my project in 0.60.4.
  7. Logging the server (only it doesn’t show anything, because it goes to the catch error in the fetch) 0.60.4 version can be found on my git here: https://github.com/CPhilipse/httprequest. Same with the 0.59.8 version: https://github.com/CPhilipse/testhttprequest.
  8. Using the fetch example from React Native Networking (docs), but then with my url. Gives same error. When I use the url from the example, it works. Which is the reason I believe that the cause is of my url, only I don’t see what.
async handleRegistration(){
        console.log(this.state.name, this.state.email, this.state.password);
        await fetch('http://my_ip:3000/newCustomer', {
            method: 'POST', 
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ 
                "name": this.state.name,
                "email": this.state.email,
                "password": this.state.password
            })
        })
            .then(response => response.json())
            .then(responseJson => console.log(responseJson))
            .catch((error) =>{
                console.warn(error);
            });
    }

This is my fetch code. The uri newCustomer have I defined in Routes.js (node server) Same with the port 3000.

I expect for the fetch to just work and that the data to post. To the very least, not give this error. What I get is this error message which I’ve been struggling with for days now: TypeError: Network Request Failed. Am I missing something?

3

Answers


  1. You should use either async/await or promise chaining, but not both at the same time. Try something like this:

    try {
        const response = await fetch('http://my_ip:3000/newCustomer', {
            method: 'POST', 
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ 
                "name": this.state.name,
                "email": this.state.email,
                "password": this.state.password
            })
        );
    
        const data = await response.json();
    } catch (e) {
        console.warn(error);
    }
    
    Login or Signup to reply.
  2. Network Error points to your second point, I use my ip4 address (not localhost).

    As you are using your mobile device, and using the internal ip (from ipconfig) of the server, the Mobile and Server needs to be on the same network. So that the mobile can access the server IP address, to put it simply both needs to be connected to the same router.

    But if you are not in the same network, you may need to port forward the server ip:port and access the server from your mobile device using the Public IP(google What is my IP), not the internal private IP.

    Login or Signup to reply.
  3. In my case, it was related with the server certificates.

    I was running a node.js https server, it was being accessed from web browser and through postman via POST method. But fetch method on react native android app was giving TypeError: Network request failed which is very poorly informed.

    After so much work, i found the mistake on my certificates. I was using let’s encrypt certificate and generated using win-acme tool. It generates for .pem files for servers such as node.js. I was using key.pem (make settings.json>PrivateKeyExportable:true) and crt.pem which caused error and I changed the crt.pem with chain.pem file. and then işte bu* it worked.

    ** a turkish expression means that’s it.

    Here is the code for node.js server:

    const https = require("https"),
      fs = require("fs");
    
    const options = {
     key: fs.readFileSync('siteadresi.com-key.pem', 'utf8'),
      cert: fs.readFileSync('siteadresi.com-chain.pem', 'utf8') //must be chain.pem
    };
    const express = require('express')
    const qs=require('qs')
    const app = express()
    const port = 3000
    app.get('/', (req, res) => {
      res.send('Hello World!')
    })
    
    app.listen(port, () => {
      console.log(`Example app listening at http://localhost:${port}`)
    })
    
    https.createServer(options, app).listen(8080); // allow 8080 port on firewall
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search