'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



Solution 1:[1]

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.

Solution 2:[2]

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

Solution 3:[3]

In addition to @jacobhobson answer, I had also used some parameters to made it work.

app.use(cors({origin: true, credentials: true}));

Solution 4:[4]

I was having same issue on production on digital ocean droplet. I was using axios in ReactJS to call Node.js API.

Although I included cors

const cors = require('cors');
app.use(cors());

But I still had to add

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

before calling out my controller. And it worked for me. There I realized that cors is not working properly. So I uninstalled and installed them again and It Works!

Complete code is here.

So either you use

 app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
  res.header("Access-Control-Allow-Headers", "x-access-token, Origin, X-Requested-With, Content-Type, Accept");
  next();
});

or use

app.use(cors());

It's the same.

Solution 5:[5]

Make sure you have the same port number in cors({ origin : [ "http://localhost:3001"]}) and the .env file.

Solution 6:[6]

In my case I used "https" instead of "http", check that too.

Solution 7:[7]

I received a network error with axios 0.27.2 when I was trying to upload an image to our server. After I set headers like below no error is received.

headers:{"Accept":"application/json, text/plain, /","Content-Type": "multipart/form-data"}

and you need to check with your api request's body type in your collection like if it's form-data or x-wwww-form-urlencoded or ..etc.

Solution 8:[8]

In my case it happened when my internet connection was unstable. Make sure your internet connection is stable.

Solution 9:[9]

In my case I had set all the needed configs mentioned above in NodeJs but I still got the error. I was using port 6000 in NodeJs and then I changed it to port 5000 and the problem was solved.
So just change the port if you have done all the alternatives.

Solution 10:[10]

This is happening because of restrict-origin-when-cross-origin policy.Browser sends a pre-flight request to know whom the API server wants to share the resources. So you have to set origin there in API server and send some status.After that the browser allow to send the request to the API server.

Here is the code.I am running front-end on localhost:8000 and api server is running on port 6000.

const cors = require("cors");

app.options("*", cors({ origin: 'http://localhost:8000', optionsSuccessStatus: 200 }));

app.use(cors({ origin: "http://localhost:8000", optionsSuccessStatus: 200 }));

I have set origin as my front-end url, If You set it to true , then it will allow only port 8000 to access rosource, and front-end running on port 8000 can not access this resource. Use this middleware before route in api server.

Solution 11:[11]

In my case I was running app on localhost:3001 while I passed cors origin:http://localhost:3000

Solution 12:[12]

I have resolved my issue by adding this header.

var data = new FormData();
              data.append('request', 'CompaniesData');
           var config = {
                 method: 'post',
                 url: baseUrl, headers:{"Accept":"application/json, text/plain, /","Content-Type": "multipart/form-data"},
                    data : data
                  };
            
                 axios(config)
    .then(function (response) {
      console.log(JSON.stringify(response.data));
    })
    .catch(function (error) {
      console.log(error);
    });

Solution 13:[13]

i'm using axios in react-native as android and .net as backend, i have same issue but i can't solve the problem. I think it is security problem when i type the url in chrome it warns me about that in emulator.

axios("http://10.0.2.2:5001/api/Users/getall")
  .then((result) => setUsers(result.data.data))
  .then((json) => {
    return json.data;
  })
  .catch((error) => {
    console.error(error);
  })
  .then((response) => response.parse());

Solution 14:[14]

Check to see if the AD blocker is installed