Axios react native network error

This is long-standing problem for me and I can't find solution at all. Within my react native project(react-native-cli), I send request to server using axios package. But when I'm testing with my

This is long-standing problem for me and I can’t find solution at all.

Within my react native project(react-native-cli), I send request to server using axios package.
But when I’m testing with my android phone, it gives [Error: Network Error].
With emulator, it’s okay.

I’m sure this is not back-end problem because I’ve tested with several servers.
And I also used fetch instead but got same error.

Here is version information.

"axios": "^0.19.0",
"react": "16.9.0",
"react-native": "0.61.5",

Sometimes, it’s working on android phone too.
This problem is biggest mystery and I suffered for a long time.

Somebody who experienced this issue, please alive me.
Thank you for careful reading.

Sometimes, it’s not working even with android emulator. But after deleted original emulator and created new emulator, it’s working.

const serverUrl = "https://server.com";
axios.post(serverUrl + "/api/candidates/login", {
            "email": this.state.email ,
            "password": this.state.password
        }, {
            headers: {
                'Content-Type': 'application/json'
            }
        }).then((response) => {
                console.log(response.data);
        }).catch((error) => {
                console.log(error);
        })

Describe the bug

While making any post request using Axios package. I am getting a Network error. While the same API seems to be working perfectly fine with Android devices. It is not an issue with the API.

To Reproduce

Axios post request throws a network error message. If I make the call again inside the catch block then it works fine.

axios
      .post(
        base_url + 'generatePaymentIntent',
        {
          // unit_id: 1,
          token: obj,
          order_type: 'ORD',
          order_data: {
            order_type: order_type,
            apt_id: apt_id,
          },
        },
        Loginheader,
      )
        .then(item => {
        this.setState({
          loading: false,
        });
        console.log('--------generate intent----------');
          console.log(item);
        if (item.data.code === 200) {
          const {price} = item.data.data.order_data;
          

          this.displayPaymentModal(
            'Confirm Payment',
            `Final Price: $${price}`,
            this.props.navigation,
            item.data.code,
            'Make Payment',
            item.data.data,
          );
        }
      })
      .catch(e => {
        this.setState({
          loading: false,
        });
        console.log('--------catch generate intent----------');
        // console.log(e.response);
        // const {message, code} = e.response;
        // this.retryPopup(
        //   `Error getting payment Intent`,
        //   message,
        //   '',
        //   code,
        //   'onetime',
        // );
        console.log(e.response);

        console.log(JSON.stringify(e));

        if (e.message === 'Network Error') {
          // this.makeOneTimePayment(order_type, apt_id);
          this.retryPopup(
              `Error getting payment Intent`,
              'RETRY',
              '',
              '400',
              'onetime',
            );
        }
      });

Expected behavior

It shouldn’t through network error. What should be done to fix this behavior specifically for iOS devices/simulators.

Environment

  • Axios Version [e.g. 0.19.2]
  • Additional Library Versions [e.g. React 16.9.0, React Native 0.62.2]

Additional context/Screenshots

N/A

Содержание

  1. Network error in axios and react-native after bundle release #26201
  2. Comments
  3. Steps To Reproduce
  4. «NETWORK ERROR» when making API call in react-native Android, while works in iOS #31045
  5. Comments
  6. Description
  7. React Native version:
  8. Steps To Reproduce
  9. Expected Results
  10. Snack, code example, screenshot, or link to a repository:
  11. Using Axios with React Native to manage API requests
  12. Introduction
  13. Introduction to Axios
  14. Setting up a simple React Native application using the Expo CLI
  15. Introduction to Axios
  16. How to install Axios
  17. How to make requests to an API using Axios
  18. Over 200k developers use LogRocket to create better digital experiences
  19. How to make multiple concurrent API requests using Axios
  20. How to abort network request in Axios
  21. How to create an instance of Axios
  22. Using Axios with React Native to manage API requests
  23. More great articles from LogRocket:
  24. How to manage API keys in React Native
  25. Managing application state in the network request-response cycle
  26. How to make GET request using Axios in React Native
  27. How to make POST request using Axios in React Native
  28. How to make a PUT request using Axios in React Native
  29. How to make a DELETE request using Axios in React Native
  30. Conclusion
  31. LogRocket: Instantly recreate issues in your React Native apps.

Network error in axios and react-native after bundle release #26201

I’m using react-native and axios to request,in debug model,everything is fine,but when bundle release,it occurs to the ‘Network error’ in my phone.
React Native version:0.60.4

System:
OS: Windows 10
CPU: (8) x64 Intel(R) Core(TM) i7-4790 CPU @ 3.60GHz
Memory: 2.70 GB / 7.89 GB
Binaries:
Node: 10.15.3 — D:nodenode.EXE
Yarn: 1.16.0 — D:nodeyarn.CMD
npm: 6.4.1 — D:nodenpm.CMD

Steps To Reproduce

  1. cd android
  2. ./gradlew assembleRelease
  3. and install the bundle apk file in my phone
  4. when i request use axios,the error just happended
  5. but when i run react-native run-android,everything is fine.

Describe what you expected to happen:

it is normal in bundle release.

Snack, code example, screenshot, or link to a repository:

The text was updated successfully, but these errors were encountered:

Источник

«NETWORK ERROR» when making API call in react-native Android, while works in iOS #31045

Please provide all the information requested. Issues that do not follow this format are likely to stall.

Description

API calls not working in Android devices, while its working in iOS simulator and device

My network_security_config.xml

I’ve included this file (network_security_config.xml) in AndroidManifest.xml (android/app/src/main) too.

My FLIPPER_VERSION

Also I’ve commented out

API calls are successfully working in iOS devices but not working in android.

React Native version:

System:
OS: macOS 11.2.1
CPU: (8) x64 Apple M1
Memory: 33.83 MB / 8.00 GB
Shell: 5.8 — /bin/zsh
Binaries:
Node: 14.15.3 — /usr/local/bin/node
Yarn: Not Found
npm: 6.14.9 — /usr/local/bin/npm
Watchman: Not Found
Managers:
CocoaPods: 1.10.1 — /usr/local/bin/pod
SDKs:
iOS SDK:
Platforms: iOS 14.4, DriverKit 20.2, macOS 11.1, tvOS 14.3, watchOS 7.2
Android SDK:
API Levels: 29
Build Tools: 28.0.3, 29.0.2
System Images: android-29 | Intel x86 Atom_64
Android NDK: Not Found
IDEs:
Android Studio: 4.1 AI-201.8743.12.41.7042882
Xcode: 12.4/12D4e — /usr/bin/xcodebuild
Languages:
Java: 1.8.0_282 — /usr/bin/javac
Python: 2.7.16 — /usr/bin/python
npmPackages:
@react-native-community/cli: Not Found
react: ^16.13.1 => 16.14.0
react-native: ^0.63.2 => 0.63.4
react-native-macos: Not Found
npmGlobalPackages:
react-native: Not Found

Steps To Reproduce

Provide a detailed list of steps that reproduce the issue.

  1. Tried making API calls in Android.
  2. Its not working, its working in iOS devices.

Expected Results

Successful API Calls.

Snack, code example, screenshot, or link to a repository:

Please provide a Snack (https://snack.expo.io/), a link to a repository on GitHub, or provide a minimal code example that reproduces the problem.
You may provide a screenshot of the application if you think it is relevant to your bug report.
Here are some tips for providing a minimal example: https://stackoverflow.com/help/mcve

The text was updated successfully, but these errors were encountered:

Источник

Using Axios with React Native to manage API requests

October 8, 2021 10 min read 3009

Introduction

More often than not, you will need to make network requests to an API when building a web or mobile application. You can make these network requests to authenticate a user, update a resource, or retrieve a resource from your own server or third party APIs. The Fetch API comes in handy if you want to make API requests in a browser environment.

React Native also has a built-in Fetch API similar to the browser’s, specifically for networking with an API from your mobile application. However, there are alternative libraries, such as Axios, that you can use instead of relying on the native Fetch API.

The built-in fetch API might suffice if you only want to retrieve a resource from the server. Axios may be a better option for more complex networking requirements because it comes with additional features, such as the interception of network requests and responses.

Additionally, among other reasons, most developers prefer Axios over the built-in fetch API because of its isomorphic nature and out-of-the-box JSON transformation.

In this article, you will learn how to manage API requests using Axios in a React Native application.

Introduction to Axios

Axios is a popular, isomorphic HTTP client. That means it can run in the browser and the Node runtime environment. As a result, you can use the same codebase for making API requests in Node, in the browser, and in React Native.

Axios has several features such as support for the Promise API, automatic JSON transformation, and interception of network requests and responses, among others.

Setting up a simple React Native application using the Expo CLI

We will use a simple React Native application set up using Expo’s managed workflow for this tutorial.

If you have a React Native application set up already, you can continue to the next section. Otherwise, there are setup instructions in the React Native documentation for Expo’s managed workflow that can get you up and running within minutes.

Introduction to Axios

Axios is one of the easiest HTTP clients to learn and use. Making an API request is as simple as passing a configuration object to Axios or invoking the appropriate method with the necessary arguments. You will learn the basics of Axios in this section.

The features highlighted in the following sub-sections are the most common features you will use when working with Axios.

How to install Axios

Depending on which package manager you use, type one of the commands below on a terminal window and hit return to install Axios:

How to make requests to an API using Axios

When making a call to an API using Axios, you can pass a configuration object to Axios or invoke a method for the corresponding CRUD operation you want to perform.

For example, you can make a GET request to the /api/users endpoint in one of the following two ways:

You can also use async/await instead of using Promise chaining like in the above example.

Over 200k developers use LogRocket to create better digital experiences

There are several other fields such as baseURL , transformRequest , transformResponse , and headers , among others, which you can include in the configuration object you pass to Axios:

Unlike the built-in Fetch API, Axios will convert the response to JSON for you out of the box.

How to make multiple concurrent API requests using Axios

You can use the Promise.all or Promise.allSettled method of the Promise API with Axios to make multiple concurrent API requests from a React Native application.

All the API requests will be successful in the code snippet below; change the URI passed to the axios.get method to non-existent ones to see what happens if some of the requests are not successful:

Take note that the Promise.all method immediately rejects if one of the input Promises rejects. Use Promise.all if you want to see all or none of the API requests be successful.

Promise.allSettled , on the other hand, waits for all of the input Promises to either reject or fulfill. Then, you can check the fulfilled or rejected status of each response object.

How to abort network request in Axios

Axios provides functionality for aborting network requests. A typical use case of this feature in React Native is the cancellation of network requests in the useEffect hook when a component is unmounted while data is still in flight.

You can read the code snippet below to understand how to use this functionality:

How to create an instance of Axios

You can also create an instance of Axios with a custom configuration. Then, use the methods exposed by the instance to make network requests.

Axios will merge the configuration object passed while creating the instance with the configuration passed to the instance method:

Using Axios with React Native to manage API requests

In this section, you will learn to manage API requests using Axios in a React Native application. You will use Axios to perform a simple CRUD (Create, Read, Update, and Delete) operation.

More great articles from LogRocket:

  • Don’t miss a moment with The Replay, a curated newsletter from LogRocket
  • Learn how LogRocket’s Galileo cuts through the noise to proactively resolve issues in your app
  • Use React’s useEffect to optimize your application’s performance
  • Switch between multiple versions of Node
  • Discover how to animate your React app with AnimXYZ
  • Explore Tauri, a new framework for building binaries
  • Compare NestJS vs. Express.js

How to manage API keys in React Native

Most third party APIs require secret credentials to access. It is not a good idea to keep your secret API keys in your source code on the client side. If you do, anybody who inspects the code for your bundled application will have access to your private key.

One of the recommended methods of managing your API key is to create an orchestration layer between the third party API and your application. For example, you can use a serverless function to securely access your API key.

Your app will make a call to the endpoint exposed by the serverless function. The serverless function will securely access your API key, make a call to the third party API, retrieve the resource you need, and relay it to your mobile application.

Managing application state in the network request-response cycle

When you initiate a network request to an API, the request will either succeed or fail. Therefore, it is important to keep track of the different states of your app from the time of requesting until you receive a response from the server.

While the data is still in flight, you can display a loading indicator. If the CRUD operation is successful, you show a “success” message to the user. If it fails, you display an appropriate error message.

This is important because a client using your application might have a slow internet connection or no internet access. The API server may sometimes experience downtime. Tracking the state of your application and displaying appropriate messages will provide a good user experience.

We shall use the reqres REST API in this article. It is a placeholder API comprising of dummy data. You can play with the endpoints using API testing tools such as Postman or Insomnia.

How to make GET request using Axios in React Native

In this section, we shall make a GET request to the /api/users endpoint to retrieve a user. GET is the HTTP method you use if you want to request a resource from the server.

We are storing the user ID in state as shown in the code snippet below. You can change the user ID inside the onPress event handler attached to the Load User button. Changing the user ID will trigger a GET request to the API inside the useEffect hook.

After triggering a network request, we display a loading indicator on the screen. If we fetch the data successfully, we update state and remove the loading indicator. If we fail to retrieve the data for some reason, we stop the loading indicator and display an appropriate error message.

We abort the network request in the cleanup function if the user decides to close the app before getting a response from the server. Check the return value of the effect function in the useEffect hook.

Here’s what the code for this looks like in the App.js component:

In the above component, we use the useEffect hook to perform side effects, like fetching data from an API. However, this might change in future versions of React. You can check the React documentation for more about React Suspense; it is a data fetching feature that will land in a stable release of React very soon.

How to make POST request using Axios in React Native

In this section, you will learn how to make a POST request. POST is the HTTP method you use to send data to the server for updating or creating a resource.

The placeholder API we are using exposes the /api/users endpoint for creating a resource. You will get a response with a 201 status code after successfully creating the resource.

Making a POST request in Axios is similar to making a GET request. Most of the time, POST requests are made with user-generated data submitted using a form. The submitted data can be from log in, sign up, or feedback forms from your clients. Such data requires validation on the client side before it is submitted.

You can use one of the form packages for data validation when building a complex applications. Most of the packages are well architected and optimized, and have a great community behind them. However, before integrating a library in your application, explore the tradeoffs. Especially the additional bundle size you are adding to your app, and potential security vulnerabilities it might introduce.

There are two main React packages for managing forms. These packages are Formik and React Hook Form. You can find plenty of articles on form validation in React if you are interested.

We have a React Native form for the user’s full name and email in the code snippet below. Both TextInput components are controlled components. Ideally, as the user fills the form, you perform data validation in real time. However, that is not the case here, because form data validation is outside the scope of this article.

After clicking the submit button, the TextInput fields and the submit button are disabled before you display a message to show you are creating the resource. Disabling the submit button ensures the user doesn’t make multiple submissions.

After successfully submitting a POST request, you display a success message to the user:

How to make a PUT request using Axios in React Native

Updating a resource requires either the PUT or PATCH method, though I will focus on PUT.

If a resource exists, using the PUT method completely overwrites it, and creates a new resource if it doesn’t. On the other hand, PATCH makes partial updates to the resource if it exists and does nothing if it doesn’t.

Making a PUT request to an API is similar to making a POST request. The only difference is in the configuration object you pass to Axios, or the HTTP method you need to invoke to make a PUT request to the API.

You can replace the onSubmitFormHandler of the POST request with the code below to make a PUT request. For completeness, I am using Promise chaining rather than async/await in the event handler below:

How to make a DELETE request using Axios in React Native

You can make DELETE requests using Axios the same way you make POST and PUT requests.

Just like its name suggests, a DELETE request will delete a resource from the server side. You can replace the onSubmitFormHandler of the code for making a POST request with the event handler below to make a DELETE request. The rest of the code remains the same:

Conclusion

Making network requests to an API is inevitable when you are building a mobile application, and Axios is one of the most popular HTTP clients out there. It comes with added functionalities, making networking as simple as possible.

The APIs your app interacts with can be self hosted or third party APIs. For improved user experience, effective management of the network request-response cycle is paramount.

On the flip side, you need to weigh the tradeoffs of adding third party packages like Axios to your mobile application. Though Axios is a popular and well-maintained package, it will increase your bundle size by 367kB according to Packagephobia.

Though that bundle size might look like a small addition to your app when using powerful mobile devices, you need to think about the effect it will have on your users with less powerful mobile devices. In the same vein, you need to ensure third party packages like Axios do not introduce security vulnerabilities to your application.

LogRocket: Instantly recreate issues in your React Native apps.

LogRocket is a React Native monitoring solution that helps you reproduce issues instantly, prioritize bugs, and understand performance in your React Native apps.

LogRocket also helps you increase conversion rates and product usage by showing you exactly how users are interacting with your app. LogRocket’s product analytics features surface the reasons why users don’t complete a particular flow or don’t adopt a new feature.

Start proactively monitoring your React Native apps — try LogRocket for free.

Источник

React is one of the most popular web development frameworks around at the time. React owes a lot of its popularity to the availability of hundreds of different plugins and libraries that users can download and use to enhance their workflows.

Axios is one such library that can make sending requests back and forth to APIs and catching any errors rather easy. In this article, we’re talking about how to fix the “Axioserror: Network error” bug. 

Also read: Flutter vs React Native vs Ionic vs Xamarin


What causes this error?

This is a generic network error in Axios that can be triggered even when your API responds with a status code. There are a number of reasons why this might happen:

  • Incorrect requests.
  • Bug in Axios.
  • Status code bug in the API.

You can try out the following two fixes. 

Formulate proper API URLs

If you’re using APIs hosted internally on your network, it’s common practice to just refer to the server’s IP address followed by the API path to send requests and fetch any data. However, if you’re not adding HTTP:// to your requests, chances are Axios will give out a network error. 

Instead of writing your API URLs like this

123.45.67.890/API/Path

Write them like this

http://123.45.67.890/API/Path

Use Cross-Origin Resource Sharing (CORS)

If you’re creating your API using NodeJS, you need to use CORS to get your APIs working. Simply add the following snippet to your server file. 

// This should already be declared in your API file
var app = express();

// ADD THIS
var cors = require('cors');
app.use(cors());

Additionally, you might also have to include the following line before calling your controller in case CORS isn’t working properly. 

res.header( "Access-Control-Allow-Origin" );

Also read: React vs Next.js: 3 talking points

Yadullah Abidi

Someone who writes/edits/shoots/hosts all things tech and when he’s not, streams himself racing virtual cars.

You can contact him here: [email protected]

Хром эту ошибку не идентифицирует, но выдает код и судя по всему дело во взаимодействии axios и API (но это не точно) https://www.reddit.com/r/reactjs/comments/66v4pg/c… .
5bb1e3ea7f479336371832.png5bb1e3f720de6243228843.png
Mozilla выводит: «Запрос из постороннего источника заблокирован: Политика одного источника запрещает чтение удаленного ресурса на «тут ссылка на апи». (Причина: не удалось выполнить запрос CORS).» https://developer.mozilla.org/ru/docs/Web/HTTP/COR…
Вот запрос:

var data = "username=юзернейм&password=пароль"
axios("Cсылка на апи", {
method: 'POST',
async: true,
crossDomain: true,
data: data,
headers: {
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
"accept-language": "en-US,en;q=0.9,ru;q=0.8",
"content-type": "application/x-www-form-urlencoded",
}
}).then((response) => {
console.log(response)
})
.catch((error) => {
console.log(error)
})

Это апишка авторизации и авторизация успешно проходит, но вскоре выбивает обратно, может ли быть проблема на стороне клиента (моей)? Можно ли что-то предпринять?
с заголовками я эксперементировал, но безрезультатно.

I am making a POST request to server to upload an image and sending formdata using axios in react-native. i am getting «Network Error». i also try fetch but nothing work.using react native image picker libeary for select image.in postman api working fine

        formData.append('title', Title);
        formData.append('class_id', selectClass._id)
        formData.append('subject_id', checkSelected)
        formData.append('teacher_id', userId)
        formData.append('description', lecture);
        formData.append('type', 'image');

       var arr=[];
       arr.push(imageSource)
       arr.map((file,index)=>{
       formData.append('file',{
       uri:file.path,
       type:file.type,
       name:file.name
       })
       })


       axios({
       method: 'post',
       url: URL + 'admin/assignment/create',
       data: data,
       headers: {
       "content-type": "multipart/form-data",
       'x-auth-token': token,
        },
       })
     .then(function (response) {
    //handle success
    console.log('axios assigment post',response);
      })
   .catch(function (response) {
     //handle error
      console.log('axios assigment post',response);
    });

Kevin Ilondo

If you are currently working on an app with React Native and you are using Laravel as your backend, you have probably encountered this problem.
And this article will help you solve this problem with just ONE SIMPLE TRICK.

SOMETIMES THIS PROBLEM IS CAUSED BY HOW YOU START YOUR LARAVEL APP

We all know how to start a Laravel server with the simple php artisan serve command and that’s the problem.
By starting your Laravel app like that it creates a link for your app which is localhost:8000 (the port may be different for you, it might be 3000, 8080 or anything else but we will use 8000 for this tutorial).
When making an HTTP Request with React Native, there is some kind of conflict because your Android app is run on an emulator which uses localhost too, and instead of sending the request to the localhost on your computer, it sends the request to the phone itself but with a different port and that is why you are getting this error.

THE TRICK THAT HELPED ME

Microsoft Windows [Version 6.3.9600]
(c) 2013 Microsoft Corporation. All rights reserved.

D:xampphtdocsprojectslaravelblog>php artisan serve --host 10.10.10.2 --port="8000"
Laravel development server started: http://10.10.10.2:8000

Enter fullscreen mode

Exit fullscreen mode

Just start the server by giving an IP address and a port
It’s just that simple! Start your app as usual but don’t forget to give an IP address and a port, this will help you solve the Network Request Failed error.

NOTE: Replace 10.10.10.2 with your own IP Address, this is just an example.

//with axios
await axios.post('http://10.10.10.2:8000/api/user/login', data, headers)
    .then(res => {
      console.log(res.data)
    })
//with Fetch
await fetch('http://10.10.10.2:8000/api/user/login', {
method: "POST",
headers: headers //put your headers,
body: body //put the body here
})

Enter fullscreen mode

Exit fullscreen mode

And on your mobile app, make sure to use the correct URL in your request.
Make sure that CORS is enabled in your backend to avoid errors related to CORS. Next time I will make make a detailed post about how to enable it and how to solve issues related to CORS.

CONCLUSION

Start your Laravel app and enter your IP address and a port
Use the URL in your HTTP Request.
That’s it, I hope this post was useful to you and happy coding!

Понравилась статья? Поделить с друзьями:
  • Axios interceptor error
  • Axios get error status code
  • Axios get error response
  • Axios error type typescript
  • Axios error self signed certificate