83

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

Mirakurun
  • 4,859
  • 5
  • 16
  • 32

17 Answers17

82

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.

jacobhobson
  • 1,075
  • 9
  • 14
  • 5
    I am not using Express. I am using Axios in ReactJS app. What can I do to use CORS in axios? – Ahmed Aug 12 '19 at 21:13
  • 1
    One important point is to add the cors middleware before the code that you handle the request – Deniz Ozger Aug 25 '20 at 19:22
  • 4
    THANKS!, Life saving. I was trying to run an angular app that talked to node from my phone, and it did not worked. Even when it worked from my computer. If node cannot find CORS "module not found", just run npm install cors. – Ramon Araujo Sep 17 '20 at 08:01
  • 2
    this answer apply also for NestJS, I got the same error in the client side, and had to add `{ cors: true }` to `NestFactory.create`. - ,,,,, `app = await NestFactory.create(AppModule, { cors: true }); ` – Ofir G Mar 26 '21 at 14:48
  • I am using django. How can I solve this issue? – Sumit May 02 '21 at 16:34
17

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.

phoenix
  • 7,988
  • 6
  • 39
  • 45
Mahdieh Shavandi
  • 4,906
  • 32
  • 41
13

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

Samil Kahraman
  • 432
  • 6
  • 13
7

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

app.use(cors({origin: true, credentials: true}));
Tiago Barroso
  • 329
  • 4
  • 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.

  • and where I should include cors ``` const cors = require('cors'); app.use(cors()); ``` ? – jhon Jul 04 '20 at 08:23
  • You can use it before calling your routes in server.js or if you are using some middleware then you can put these lines there. P.S. I've updated my answer as well. – Hassaan Rana Jul 14 '20 at 17:42
  • 1
    I have use `app.use(cors());` though it is showing network error. But not every time I am receiving this error. I am calling an API for the video uploading. After several times calling it is throwing me the network error. – Jayna Tanawala Aug 17 '21 at 06:04
  • @JaynaTanawala Have you installed cors? Try running "npm install cors --save" – Hassaan Rana Nov 30 '21 at 07:58
  • yes. Have installed it. – Jayna Tanawala Dec 02 '21 at 06:03
4

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.

Skoua
  • 3,373
  • 3
  • 38
  • 51
A.A.
  • 81
  • 2
3

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

Elletlar
  • 3,136
  • 7
  • 32
  • 38
tejas e
  • 74
  • 3
3

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

Amir Mehrnam
  • 346
  • 5
  • 5
1

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);
    });
Ali Raza Khan
  • 181
  • 1
  • 4
1
  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

UdayanBKamble
  • 99
  • 1
  • 7
1

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

Godfather
  • 21
  • 3
1

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

1

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.

0

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.

DIPIKESH KUMAR
  • 129
  • 1
  • 6
0

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
       }
});
Ben
  • 395
  • 1
  • 5
  • 16
0

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

gokul raj
  • 21
  • 3
-1

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