Home > database >  Unable to handle net::ERR_CONNECTION_REFUSED in React
Unable to handle net::ERR_CONNECTION_REFUSED in React

Time:07-09

I am trying a post request to http://localhost:5000/run. If the server is not running then trying to throw "Please retry again" to client.

try{
    const {data} = await axios.post("http://localhost:5000/run",payload);
    setOutput(data.output);
}
catch ({ response }) {
  if (response) {
    const errMsg = response.data.err.stderr;
    setOutput(errMsg);
  } else {
    setOutput("Please retry submitting.");
  }
}

enter image description here

when the server is running proper error is received but not when the server is offline. Anything missing from the code?

CodePudding user response:

Please try this code:

try {
  const { data } = await axios.post("http://localhost:5000/run", payload);
  setOutput(data.output);
} catch (error) {
  if (!error.response) {
    setOutput("Error: Network Error");
  } else if (error.response.data) {
    setOutput(error.response.data.message);
  } else {
    setOutput("Something went wrong. (Like CORS)");
  }
}

CodePudding user response:

You need to try using response.response.data.error for displaying error in your case instead of response.data.err.stderr. So here you are getting error data from response :

try{
    const {data} = await axios.post("http://localhost:5000/run",payload);
    setOutput(data.output);
}
catch ({ response }) {
  if (response) {
    const errMsg = response.response.data.error;
    setOutput(errMsg);
  } else {
    setOutput("Please retry submitting.");
  }
}

Reference discussion here.

CodePudding user response:

Here is the solution that worked . Thanks all for your inputs

try{
    const {data} = await axios.post("http://localhost:5000/run",payload);
    setOutput(data.output);
    }
    catch (error) {
      if (error.response.data) {
        setOutput(error.response.data.err.stderr);
      } 
      else {
        setOutput("Error connecting to server!");
      }
    }
  • Related