Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: Axios Network Error

This is my first time using axios and I have encountered an error.

  axios.get(
    `http://someurl.com/page1?param1=1&param2=${param2_id}`
  )
  .then(function(response) {
    alert();
  })
  .catch(function(error) {
    console.log(error);
  });

With the right url and parameters, when I check network requests I indeed get the right answer from my server, but when I open console I see that it didn't call the callback, but instead it caught an error.

Error: Network Error Stack trace: createError@http://localhost:3000/static/js/bundle.js:2188:15 handleError@http://localhost:3000/static/js/bundle.js:1717:14

like image 859
Mirakurun Avatar asked Aug 31 '17 11:08

Mirakurun


People also ask

How do I fix an Axios network error?

To Solve Error: Network Error Stack trace Error If You are using localhost URL in your Axios Then You Need to Put HTTP:// before your URL and then you have to use API. For example: const url = “http://localhost:4000/api/get_users”; Now, your error must be solved.

How do you handle errors in Axios?

axios. get('/user/12345') . catch(function (error) { if (error.

What is network error?

It may happen that your smartphone loses internet access overnight, after being switched off, without any modification made to the network settings. You will notice, however, that some applications are still able to download data, while others won't synchronize.


3 Answers

If Creating an API Using NodeJS


Your Express app needs to use CORS (Cross-Origin Resource Sharing). Add the following 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());

For fuller understanding of CORS, please read the Mozilla Documentation on CORS.

like image 185
jacobhobson Avatar answered Oct 02 '22 23:10

jacobhobson


my problem was about the url I was requesting to. I hadn't inserted http:// at the beginning of my url. I mean I was requesting to a url like 92.920.920.920/api/Token instead of http://92.920.920.920/api/Token. adding http:// solved my problem.

like image 28
Mahdieh Shavandi Avatar answered Oct 03 '22 00:10

Mahdieh Shavandi


It happens when you work on localhost and forgot to add http://

Wrong Usage

  const headers = {
    "Content-Type": "application/json",
    Authorization: apiKey,
  };
  const url = "localhost:5000/api/expenses/get-expenses";

  axios.get(url, { headers });

  // NETWORK ERROR

The correct one is

  const headers = {
    "Content-Type": "application/json",
    Authorization: apiKey,
  };
  const url = "http://localhost:5000/api/expenses/get-expenses";

  axios.get(url, { headers });

  // WORKS FINE IF YOU HANDLED CORS CORRECTLY IN THE SERVER SIDE

like image 27
Samil Kahraman Avatar answered Oct 02 '22 23:10

Samil Kahraman