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.
How to fix this error?
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
Write them like this
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
Someone who writes/edits/shoots/hosts all things tech and when he’s not, streams himself racing virtual cars. You can reach out to Yadullah at [email protected], or follow him on Instagram or Twitter.