React: Axios Network Error

后端 未结 7 1597
既然无缘
既然无缘 2020-12-09 15:35

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

  axios.get(
    `http://someurl.com/page1?param1=1¶m2=${param2_id}`
  )
  .then(         


        
相关标签:
7条回答
  • 2020-12-09 16:16

    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.

    0 讨论(0)
  • 2020-12-09 16:18

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

    0 讨论(0)
  • 2020-12-09 16:19

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

    0 讨论(0)
  • 2020-12-09 16:23

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

    app.use(cors({origin: true, credentials: true}));
    
    0 讨论(0)
  • 2020-12-09 16:24

    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
    
    
    0 讨论(0)
  • 2020-12-09 16:31

    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.

    0 讨论(0)
提交回复
热议问题