Retrieve message from server after an async Axios POST - javascript

How do I retrieve message from server after calling:
await axios.post(url, data)
export const postData = async data => {
try {
let url = `${api}auth/register`;
let res = await axios.post(url, data).catch(e => console.log(e));
return res;
} catch (error) {
console.log(error);
Alert.alert("Error");
}
};
Now this function is returning undefined in console. My motive is to get the message and code from server response

Try the following
axios.post('url')
.catch(function (error) {
if (error.response) {
console.log(error.response.status);
console.log(error.response.message);
}
});

I've got the answers. 🙂
So whenever we call axios.post it gives us a .catch() function to use. If the server returns a bad status codes like 500 or 400. The control goes in .catch() and do whatever it says to. Since the control is in .catch() the function postData() does not return anything and remains undefined. Now, to retrieve the messages from the server this is what can we do.
.catch(e => console.log(e.response.data.message))

Related

Axios doesn't give neither .then or .catch response after POST

I'm trying to do a post in a localhost SQL DB with react/nodejs. Fortunately it does POST and the information goes to the DB. I wanted to put an alert() inside the .then() if it was sucessfull and another alert() inside the catch() if there was a error. The problem is that it gives both 'success' alert and 'error' alert when posting, although it posts all good in the database. Am I missing something?
const submitForm = () => {
Axios.post('http://localhost:3001/api/insert',{
manager:manager,
decisionDate:decisionDate.toLocaleDateString(),
}).then(alert('Success'))
.catch(alert('Failure'))
}
Your syntax is incorrect for the then callback, which results in an error that is then caught by catch. Update the callback to be the following:
const submitForm = () => {
Axios.post('http://localhost:3001/api/insert',{
manager:manager,
decisionDate:decisionDate.toLocaleDateString(),
}).then(() => alert('Success'))
.catch(() => alert('Failure'))
}
Your syntax is not right which results in an error that is then caught by catch clause.
Update the callback to be the following:
axios.post('http://localhost:3001/api/insert', {
manager:manager,
decisionDate:decisionDate.toLocaleDateString(),
}).then(function (response) {
console.log('Success', response);
}).catch(function (error) {
console.log(error);
});
Please refer to axios documentation

Can I display an error if the api cannot return the search?

So I am building an player tracker for players in the NBA, if someone misspells the players name or types a random thing that the api cannot fetch how can I alert that?
function getResults (query) {
fetch(`https://www.balldontlie.io/api/v1/players?search=${searchbox.value}`)
.then(player =>{
return player.json()
}) .then(displayResults);
};
function displayResults(player){
playerName.innerHTML = player.data[0].first_name;
playerLastName.innerHTML = player.data[0].last_name;
teamName.innerHTML = player.data[0].team.full_name;
playerPos.innerHTML = player.data[0].position;
}
If the request is actually throwing an error, you can use a .catch() to catch errors before they're thrown, like this:
function getResults (query) {
fetch(`https://www.balldontlie.io/api/v1/players?search=${searchbox.value}`)
.then(player => {
return player.json()
})
.then(displayResults)
.catch(displayError);
};
function displayError(error) {
// Parse and display your error in the UI
}
However, if the request is properly formatted and the API is available then fetch() will still give you the response without throwing an error. In this case, you can check the status of the response in your .then():
function getResults (query) {
fetch(`https://www.balldontlie.io/api/v1/players?search=${searchbox.value}`)
.then(response => {
if (response.ok) {
return response.json()
}
// If `response.ok` is `false`, you can get the status code for more information on why, or the API may send an error message in the body:
console.log(response.status) // Check http://httpstatuses.com/ for more info on the different statuses
response.json()
})
.then(displayResults)
.catch(displayError);
};

res.redirect causes error in .catch statement

I am using Node.js and have a database call being performed with a promise. I setup a '.then/.catch' to handle the result of the promise. That part all seems to work without any issue. After I do some processing of the data returned from the database I am attempting to 'redirect' to another route within the '.then' statement. This re-direction seems to be causing a problem with the '.catch' statement. I have no error issues if I remove the 'res.redirect'...is there a workaround? Any suggestions appreciated.
code:
const db = require('./routes/queries');
//**Query PostGres database...
db.getMembers()
.then(function(value) {
console.log('Async success!', value);
//do some processing on the data returned from the promise call here...
//if I insert a redirect here...such as "res.redirect('/_members');"...
//I get a "Caught an error! ReferenceError: res is not defined" message...?
//evidently the redirect fires the '.catch' statement below...why?
})
.catch(function(err) {
console.log('Caught an error!', err);
});
I recommend providing a reusable promise in case you need to find your members list elsewhere in your Express app
const db = require('./routes/queries');
const findMembers = () => {
return db.getMembers()
.then(members => {
return members
})
.catch(err => {
console.log('Caught an error!', err);
});
}
//inside your express app
app.get("/some_route", (req, res) => {
return findMembers()
.then(members => {
//do something with your members list
res.redirect("/redirect_route")
})
})

Handling network errors with axios and Twilio

I have an application that uses axios for it's ajax requests. When a user experiences a network issue (for example, their wifi goes out and they no longer have an internet connection while on my application), I want to make sure that only the first axios request is made, and if I detect there is a network issue, to not attempt any more requests, but instead to retry the same request until successful.
My application performs many requests, including a request every 2.5 seconds (in this example, getData). It also establishes a Twilio connection when the application initializes (it executes twilio() on initialization).
When a connection is lost, the following happens:
getData fails, resulting in a console message of this is a network error.
TwilioDevice.offline is executed. This results in two error messages: first a this is a network error. message (error message #2) when TwilioDevice.offline tries fetchToken(), and then a received an error. message (error message #3) after the fetchToken() fails.
Given #'s 1 and 2, how can I make sure that:
If I experience a network error, I only receive one error message instead of 3 saying that "there was a network error"
My app detects that there is a network error, then tries to re-establish a connection, then, if successful, resumes fetching data, Twilio tokens, etc.
Thanks! Code is below.
example code:
const getData = async () => {
try {
const response = await axios.get('api/data');
return response.data;
} catch (error) {
handleError(error);
}
};
const fetchToken = async () => {
try {
const data = await axios.get('api/twilio-token');
return data.token;
} catch (error) {
return handleError(error);
}
};
const handleError = error => {
if (!error.response) {
console.log("this is a network error.");
} else {
console.log("received an error.");
}
};
twilio.js:
import { Device as TwilioDevice } from 'twilio-client';
const registerEvents = () => {
TwilioDevice.ready(() => {
console.log('Twilio.Device is now ready for connections');
});
TwilioDevice.connect((conn) => {
console.log(`Connecting call with id ${conn.parameters.CallSid}`);
// code to start call
conn.disconnect((connection) => {
console.log(`Disconnecting call with id ${connection.parameters.CallSid}`);
// code to end call
});
});
TwilioDevice.error((error) => {
console.log("Twilio Error:");
console.log(error);
});
TwilioDevice.offline(async () => {
try {
const newTwilioToken = await fetchToken(); // error message #2
return TwilioDevice.setup(newTwilioToken);
} catch (error) {
return handleError(error); // error message #3
}
});
};
export const twilio = async () => {
try {
registerEvents();
const twilioToken = await fetchToken();
TwilioDevice.setup(twilioToken);
} catch (error) {
return handleError(error);
}
};
I would recommend making your fetchToken and getData methods to throw errors rather than handling it themselves so that they can be handled by their outer functions.
Something like,
const getData = async () => {
try {
const response = await axios.get('api/data');
return response.data;
} catch (error) {
throw (error);
}
};
const fetchToken = async () => {
try {
const data = await axios.get('api/twilio-token');
return data.token;
} catch (error) {
throw (error);
}
};
So that when you call twilio() that function can handle the error like retrying etc.

How to access response message returned from server on frontend using the fetch api in React?

Okay, this is a pretty simple question.
I am returning a 400 status error along side a message "Index should have 6 digits" message back in my response.
I am using React for my front-end. When I log the body of the response using the fetch api [console.log(response.json())], I can see that I receive it properly.
But for some reason I cannot access it any any way.
Also, I don't know why the status statusText field in the response is empty.
What am I doing wrong?
What is the defacto standard for exception handling from server side?
Thank you.
Edit - code:
errorHandler = (response) => {
if (!response.ok){
console.log(response.json());
throw Error(response.statusMessage);
}
else {
return response;
}
};
addStudent = (student) => {
createStudent(student)
.then(this.errorHandler)
.then((response) => {
console.log('new student status: ', response.status);
this.loadData();
})
.catch((error) => {
console.log(error);
});
};
You'll see that your're getting a Promise object back in your console, this means that your request simply hasn't fulfilled yet.
Chain onto the promise with .then(response => { // handle the response here })
The code should look similar to this:
fetch('/endpoint').then(response => {
console.log(response)
}
Hope this helps!
What I do is what Mike wrote above.
fetch("endpoint")
.then((response) => response.json())
.then((data) => console.log(data.message));

Categories

Resources