50

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,376
  • 4
  • 15
  • 31

17 Answers17

54

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
  • 776
  • 7
  • 14
  • 1
    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
  • 3
    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
  • 1
    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
16

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
  • 5,738
  • 3
  • 33
  • 41
Mahdieh Shavandi
  • 3,495
  • 25
  • 32
10

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
  • 286
  • 3
  • 10
4

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

app.use(cors({origin: true, credentials: true}));
Tiago Barroso
  • 209
  • 3
  • 3
3

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
2

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

Elletlar
  • 2,991
  • 7
  • 29
  • 34
tejas e
  • 66
  • 3
2

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

1

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,010
  • 3
  • 40
  • 48
A.A.
  • 11
  • 1
0

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

Yuvraj Patil
  • 6,242
  • 3
  • 46
  • 50
0

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.

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
  • 121
  • 1
  • 6
0

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

0

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

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

Check to see if the AD blocker is installed

-3

Check if your server is running and your API is connected to database.

-3

In my case, I didn't start the backend server. Make sure your backend server is running.

Jyothi
  • 9
  • 1