10

I am using React.js in macOS and when I try to call axios.get, I get Network Error. I read many other cases like mine who were using React Native and the answer to them was adding settings to allow them to use http in mac instead of https, but that setting can not be used in react js.

Any advice would be appreciated.

Error: Network Error
    at createError (createError.js:17)
    at XMLHttpRequest.handleError (xhr.js:87)

My code is like this:

try {
  const Response = await axios.get(http://xxxxx/WebServiceTest/service.svc?wsdl/GetItems, {
   
    params: {
      Number: "100",
      Id: "101",
      userName: "11",
      credential: "Test"
    }
  });
  console.log("http response = " + Response.data);
} catch (ex) {
  console.log("error.status:", ex);
}

9 Answers 9

4

Change your await to a promise, even if you put await the axios function will work asynchronously.

async functionName() {
  let response = () => {
    return new Promise(function(resolve, reject) {
      fetch('http://xxxxx/WebServiceTest/service.svc?wsdl/GetItems', {
        params: {
          Number: "100",
          Id: "101",
          userName: "11",
          credential: "Test"
        }
      }).then(response => {
        resolve(response);
      });
    });
  };
  let responseData = await response();
  console.log(responseData.data);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your reply, now I get error:"Unhandled Rejection (TypeError): Cannot read property 'get' of undefined", I searched but couldnt find a solution for that, please advice
Thanks for the answer, unfortunately I have issue connection to third party's server and waiting for them to resolve, I will test asap and let you know
Isn't this simply fetch instead of Axios? Essentially what you seem to be saying, to me, is that Axios is useless and I wouldn't think that a credible opinion, to be honest. Since Axios is highly respected generally.
4

I have found the solution in spring boot by using @CrossOrigin annotation.

@RestController
@CrossOrigin
@RequestMapping("/cus")
public class CusController{

    @Autowired
    CustomerService cus_service=null;

    @PostMapping("/save")
    public Customer saveCustomer(@RequestBody Customer customer)
    {

        if(customer!=null)
            return cus_service.saveCustomer(customer);
        else
            throw new DataNotFoundException("Data Not Available For Customer");

    }
}


Comments

2

You can simply make the following changes in your

axios.create({baseURL:" "});

make it into

const instance = axios.create(
{
        baseURL: "",
        withCredentials: false,
        headers: {
          'Access-Control-Allow-Origin' : '*',
          'Access-Control-Allow-Methods':'GET,PUT,POST,DELETE,PATCH,OPTIONS',   
      }
  })

In your case try adding the above wherever you must have created instance of your axios.If you are using default axios then consider creating custom instance following the above code.

Comments

2

your server should enable the cross origin requests, not the client. if you use backend adress for some operation you should enable for example in node.js the CQRS.

1 Comment

Can you give me the steps to do it with screenshots? So it will be easier for me and my fellow coders to understand.
0

You can use axios method in reactjs using some commands on server side code to get rid of cors policy error i have used these commands on my server side code which is in php

header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: *');
header('Access-Control-Max-Age: 1728000');
header("Content-Length: 0");
header("Content-Type: text/plain"); 

remember: add these lines immediately starting session

1 Comment

Why Allow Origin twice?
0
  1. We have to allow CORS, placing Access-Control-Allow-Origin:* in header of request may not work. Install a google extension which enables a CORS request.

  2. Make sure the credentials you provide in the request are valid.

  3. if you are passing request to the virtual homestead server, make sure the machine has been provisioned. If you are using vagrant try vagrant up --provision this will make the localhost connect to db of the homestead.

  4. Try changing the content type of the header. header:{ 'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8;application/json' } this point is very important.

Comments

0

Caso utilize um servidor back-end local, é só baixar o modulo do cors e incluir no back-end que resolve.

English: If you use a local back-end server, just download the cors module and include it in the back-end that solves it.

1 Comment

Please use 'English' as a language, or else it is very hard for others to understand.
0

In my case faced issue due to withCredentials : true after setting it to false it started working.

const axiosInstance = axios.create({timeout : 2000, baseURL : baseUrl , withCredentials : true})

In fact nothing wrong with withCredentials : true but it require few more settings which still I need to implement.

Comments

-1

I personally, when I got this error I re-checked my API link. My API link used to be "https://localhost:5000/" for my backend works. But I used to get Network error and Xhttprequest error. After searching I got to know that there is an error with my API link and that is the reason there's a Network error.

Network error arises when the connection or communication between your device and the API is not going straight, precisely you should check your API endpoints and mainly recheck your API link.

When I scanned my code for errors for several hours, I get to know that my API link was incorrect, it has to be "http://localhost:5000/". There's a huge difference between HTTP and HTTPS. I hope this answer will give you a clarity about this error.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.