TeaNyan
TeaNyan

Reputation: 5079

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

Upvotes: 97

Views: 508344

Answers (20)

Haythem Khiari
Haythem Khiari

Reputation: 9

i found the solution for those who use react native and run the app on thier own device with expo go. In the url of your API don't put localhost instead you have to put the actual IP adress of your pc.

exemple: this didn't work : ==> http://192.168.1.105:5000/api/v1/constat

you should try this :==> http://your_ip_adress:5000/api/v1/constat

if you want to know your IP Adress open the terminal and write : ipconfig /all

Upvotes: 0

saurabh yadav
saurabh yadav

Reputation: 11

In my case I was assigning string to url

like : {url : 'link' } --> this is wrong

   {url : link } --> this is correct

Upvotes: 0

work technotoil
work technotoil

Reputation: 7

If you are using localhost api so connected with the same wifi and replace localhost to IP then everything is fine......

Upvotes: -2

gokul raj
gokul raj

Reputation: 21

if you are using http:// requests there is a chance to occur this error.

To avoid the u can use https:// base url or u can enable android:usesCleartextTraffic="true" in manifest [question]: Android 8: Cleartext HTTP traffic not permitted

recommended using https: //yoururl/api not http: // your url

Upvotes: 0

Andrew James Okpainmo
Andrew James Okpainmo

Reputation: 123

Even though I had CORS in my project already, I encountered an error with the "network error" flag in axios because I was passing custom headers into axios before the post data.

The post data in axios should always be the second argument, then the custom headers last.

Upvotes: 2

The Ambidextrous
The Ambidextrous

Reputation: 117

If you are running react native in development while using real device connected via USB(and the API server is being accessed via development machine IP), ensure the development machine and the device are both connected to the same network

Upvotes: 2

Godfather
Godfather

Reputation: 61

I just want to let you know that after searching for a solution for two days, I was able to solve my error. Since the proxy was the source of the issue, I must configure a proxy in the package.json file, and I have to follow these instructions in the function that uses Axios:

try { await axios.post("user/login", formData).then((res) => { console.log(res.data); }); } catch (error) { console.log(error.response.data.message); }

and in package.json file need to add a proxy:

"proxy": "http://localhost:6000",

for better understand check this documentation: enter link description here

Upvotes: 4

UdayanBKamble
UdayanBKamble

Reputation: 109

  1. change the port number of your node server. It took more than 3 hours to solve this error. Solution ended with changing port numer which was initially set to 6000, later set to 3001. Then it worked. My server localhost base url was:

    "http://localhost:6000/data"

    I changed port number in app.listen() on server and from frontend I call that GET route in async function as await axios.get('http://localhost:3001/data'). It is working fine now.

  2. If you face the address issue: address already in use :::#port

    Then on command prompt: killall -9 node

Upvotes: 1

Ben
Ben

Reputation: 426

In my case, I'm using Hapi.js as the backend, so all I had to do is set the cors value to true as in the code below;

const server = Hapi.server({
       port: 4000,
       host: 'localhost',
       state: {
           strictHeader: false
       },
       routes: {
           cors: true
       }
});

Upvotes: 0

Melih Sahtiyan
Melih Sahtiyan

Reputation: 43

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());

Upvotes: -1

Ali Raza Khan
Ali Raza Khan

Reputation: 271

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);
    });

Upvotes: 1

A.A.
A.A.

Reputation: 251

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.

Upvotes: 4

DIPIKESH KUMAR
DIPIKESH KUMAR

Reputation: 129

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.

Upvotes: 0

Amir Mehrnam
Amir Mehrnam

Reputation: 550

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

Upvotes: 6

Samil Kahraman
Samil Kahraman

Reputation: 462

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

Upvotes: 15

tejas e
tejas e

Reputation: 74

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

Upvotes: 3

Mahdieh Shavandi
Mahdieh Shavandi

Reputation: 8645

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.

Upvotes: 16

Hassaan Rana
Hassaan Rana

Reputation: 55

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.

Upvotes: 5

Tiago Barroso
Tiago Barroso

Reputation: 387

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

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

Upvotes: 8

jacobhobson
jacobhobson

Reputation: 1195

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.

Upvotes: 95

Related Questions