How to check status in response from HTTP call - javascript

I am trying to navigate to next page if status code is 200 or response is true. But getting undefined in response.status. If I just log only response I get
{success: true, message: "login successful"}
This below code is getting undefined in console log. I am beginner to Angular and not using any service.
goToHome() {
console.log(this.login);
this.Http.post('http://localhost:3000/users/login', this.login).subscribe((response: Response) => {
console.log(response.status);
// if (resp.status === 200) {
// this.navCtrl.push(TabsPage);
// } else {
// const toast = this.toastController.create({
// message: 'User not found please try again',
// duration: 2000
// });
// toast.present();
// }
})
}

You should add options to your request, and set observe: 'response' to read full response.
this.Http.post('http://localhost:3000/users/login', this.login, { observe: 'response' })
.subscribe((response) => {
console.log(response.status);
})
More info in documentation: Reading the full response

You should use observe option ({observe: 'response'}) to get a full response that includes the response status code:
goToHome() {
this.Http.post('http://localhost:3000/users/login', this.login, {observe: 'response'})
.subscribe((response) => {
console.log(response.status);
})
}

Related

Trying to access error response 500 axios

I am not able to access the response of error - 500 in axios
export const dowloadFilePDF = (data) => {
return axios
.request({
method: 'GET',
url: `${basePath + data[0]}`,
responseType: 'blob',
headers: { Authorization: Authorization },
})
.then(response => {
console.log(response)
let fileName = response.headers['content-disposition']?.split(';')[1]?.split('=')[1]?.split('"').join('')
fileName = fileName ? fileName : 'data.pdf'
fileDownload(response.data, fileName)
})
.catch((error) => {
console.log(error.response.data)
})
}
I am not getting the response instead its returning as
data : Blob {size: 215, type: 'application/json'}
According to the documentation, you can't assume error.response will be filled in. Here's the code the documentation shows with the inline comments explaining it:
Handling Errors
axios.get('/user/12345')
.catch(function (error) {
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log(error.config);
});
There's another aspect to this as well: You're calling catch on the promise returned by then, not on the promise returned by axios. If the axios promise is rejected, you'll reach that rejection handler, but you'll also reach it if the axios promise is fulfilled but then your fulfillment handler throws an error (or returns a promise it ultimately rejects). In that latter case, the error probably won't have a response property at all.
the best way to catch errors instead of trying a lot of lines of code in the catch method by promise is using the tools in the Axios names interceptor.
interceptor has two property request and response. In response we can simulate the errors status and based on the status code we can do whatever we want. for example :
axios.interceptors.response.use(null, error => {
console.log("error : " , error);
const expectedError = error.response && error.response.status >= 400 &&
error.response.status < 500;
if (expectedError) {
return Promise.reject(error);
}
alert("unexpected error is happen");
});
if you need more help here is the original link

VueJs auth not passing

I'm having some problems with authentication with Vue.
I'm trying to check user data and return him if he is validated or not, I'm catching errors as well, but this is meant in case if some other error happens.
This is my code:
loginJWT ({ commit }, payload) {
return new Promise((resolve, reject) => {
jwt.login(payload.userDetails.email, payload.userDetails.password)
.then(response => {
// If there's user data in response
if (response.data.userData) {
// Navigate User to homepage
router.push(router.currentRoute.query.to || '/')
// Set accessToken
localStorage.setItem('accessToken', response.data.accessToken)
// Update user details
commit('UPDATE_USER_INFO', response.data.userData, {root: true})
// Set bearer token in axios
commit('SET_BEARER', response.data.accessToken)
resolve(response)
console.log(response.data.accessToken);
} else {
reject({message: 'Wrong Email or Password'})
}
})
.catch(error => { reject(error) })
})
}
As you see I have 'Wrong Email or Passoword', but this message never showed.
I tried like if(response.status === 200) and else if(response.status === 400) to catch that status and show the message, but no success anyway. Ofc when I put invalid credentials, it's returning 'Request failed with status code 400', but I want to show 'Wrong Email Or password'.
I even tried to check if first gives response status 400 before even check if there is response.data.userData like:
if(response.status == 400){
reject({message: 'Wrong Email or Password'})
}
But still not a success.
What I really want to return is the message that I'm giving from the response, I could just return the message 'something is wrong' in .catch(error), but I can't catch response.data.message like this, because I have message receiving from my backend.
Any ideas on how to resolve it?

Get a JSON response from an API?

I'm posting to an api where a failed response is output on purpose:
return response()->json([
'message' => 'Record not found',
], 422);
In Chrome dev tools I can see I get a 422 response with the response of {"message":"Record not found"}
In javascript I wish to get the message and log it, but i'm struggling to do so, here's my javascript:
axios.post('/api/test', {
name: 'test'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error) //this is Error: Request failed with status code 422
console.log(error.message); //this is blank
});
How can I get the message?
I found a code that can help you understand the catch block very well here :
axios.post('/api/test', {
name: 'test'
})
.then((response) => {
// Success
})
.catch((error) => {
// Error
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
// console.log(error.response.data);
// console.log(error.response.status);
// console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log(error.config);
});
try to catch like this:
.catch(function(error){
console.log(error);
if (error.response) {
console.log(error.response.data.message);
}
});

How to catch and handle error response 422 with Redux/Axios?

I have an action making a POST request to the server in order to update a user's password, but I'm unable to handle the error in the chained catch block.
return axios({
method: 'post',
data: {
password: currentPassword,
new_password: newPassword
},
url: `path/to/endpoint`
})
.then(response => {
dispatch(PasswordUpdateSuccess(response))
})
.catch(error => {
console.log('ERROR', error)
switch (error.type) {
case 'password_invalid':
dispatch(PasswordUpdateFailure('Incorrect current password'))
break
case 'invalid_attributes':
dispatch(PasswordUpdateFailure('Fields must not be blank'))
break
}
})
When I log the error this is what I see:
When I check the network tab I can see the response body, but for some reason I can't access the values!
Have I unknowingly made a mistake somewhere? Because I'm handling other errors from different request fine, but can't seem to work this one out.
Example
getUserList() {
return axios.get('/users')
.then(response => response.data)
.catch(error => {
if (error.response) {
console.log(error.response);
}
});
}
Check the error object for response, it will include the object you're looking for so you can do error.response.status
https://github.com/mzabriskie/axios#handling-errors
Axios is probably parsing the response. I access the error like this in my code:
axios({
method: 'post',
responseType: 'json',
url: `${SERVER_URL}/token`,
data: {
idToken,
userEmail
}
})
.then(response => {
dispatch(something(response));
})
.catch(error => {
dispatch({ type: AUTH_FAILED });
dispatch({ type: ERROR, payload: error.data.error.message });
});
From the docs:
The response for a request contains the following information.
{
// `data` is the response that was provided by the server
data: {},
// `status` is the HTTP status code from the server response
status: 200,
// `statusText` is the HTTP status message from the server response
statusText: 'OK',
// `headers` the headers that the server responded with
headers: {},
// `config` is the config that was provided to `axios` for the request
config: {}
}
So the catch(error => ) is actually just catch(response => )
EDIT:
I still dont understand why logging the error returns that stack message. I tried logging it like this. And then you can actually see that it is an object.
console.log('errorType', typeof error);
console.log('error', Object.assign({}, error));
EDIT2:
After some more looking around this is what you are trying to print. Which is a Javascipt error object. Axios then enhances this error with the config, code and reponse like this.
console.log('error', error);
console.log('errorType', typeof error);
console.log('error', Object.assign({}, error));
console.log('getOwnPropertyNames', Object.getOwnPropertyNames(error));
console.log('stackProperty', Object.getOwnPropertyDescriptor(error, 'stack'));
console.log('messageProperty', Object.getOwnPropertyDescriptor(error, 'message'));
console.log('stackEnumerable', error.propertyIsEnumerable('stack'));
console.log('messageEnumerable', error.propertyIsEnumerable('message'));
Here is the proper way to handle the error object:
axios.put(this.apiBaseEndpoint + '/' + id, input)
.then((response) => {
// Success
})
.catch((error) => {
// Error
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
// console.log(error.response.data);
// console.log(error.response.status);
// console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log(error.config);
});
Origin url https://gist.github.com/fgilio/230ccd514e9381fafa51608fcf137253
axios.post('http://localhost:8000/api/auth/register', {
username : 'test'
}).then(result => {
console.log(result.data)
}).catch(err => {
console.log(err.response.data)
})
add in catch
geting error response ==> err.response.data
I was also stumped on this for a while. I won't rehash things too much, but I thought it would be helpful to others to add my 2 cents.
The error in the code above is of type Error. What happens is the toString method is called on the error object because you are trying to print something to the console. This is implicit, a result of writing to the console. If you look at the code of toString on the error object.
Error.prototype.toString = function() {
'use strict';
var obj = Object(this);
if (obj !== this) {
throw new TypeError();
}
var name = this.name;
name = (name === undefined) ? 'Error' : String(name);
var msg = this.message;
msg = (msg === undefined) ? '' : String(msg);
if (name === '') {
return msg;
}
if (msg === '') {
return name;
}
return name + ': ' + msg;
};
So you can see above it uses the internals to build up the string to output to the console.
There are great docs on this on mozilla.
The only thing what helped me was the following:
axios.put('/api/settings', settings, {
validateStatus: status => status >= 200 && status < 300 || status === 422
})
https://stackoverflow.com/a/66285529/5849569
You can use inline if else statement like so:
.catch(error => {
dispatch({
type: authActions.AUTH_PROCESS_ERROR,
error: error.response ? error.response.data.code.toString() : 'Something went wrong, please try again.'
});
});
I recommend handling errors via Axios interceptors, individually for each case scenario:
// interceptor to catch errors
const errorInterceptor = (error) => {
// check if it's a server error
if (!error.response) {
console.log('📡 API | Network/Server error')
return Promise.reject(error)
}
// all the error responses
switch (error.response.status) {
case 400:
console.error(error.response.status, error.message)
console.log('📡 API | Nothing to display', 'Data Not Found')
break
case 401: // authentication error, logout the user
console.log('📡 API | Please login again', 'Session Expired')
localStorage.removeItem('user')
break
case 403:
console.error(error.response.status, error.message)
console.log('📡 API | Access denied', 'Data Not Found')
break
case 404:
console.error(error.response.status, error.message)
console.log('📡 API | Dataset not found', 'Data Not Found')
break
case 422:
console.error(error.response.status, error.message, error.response.data.detail)
console.log('📡 API | Validation error', 'Unprocessable Content')
break
default:
console.error(error.response.status, error.message)
}
return Promise.reject(error)
}

Aurelia | json parse uncaughtable exception?

So i am trying to make this post request, following aurelia docs:
http://aurelia.io/hub.html#/doc/article/aurelia/fetch-client/latest/http-services/3
And this is the request:
httpClient.configure(config => {
config
.withBaseUrl(baseUrl)
});
this.client = httpClient;
this.client.fetch(`/api/Register/${userName}`, {
method: "post",
body: json(loginInformation),
headers: {
'Access-Control-Allow-Origin' : '*',
'Accept': 'application/json'
}
}) .then(response => this.safelyParseJSON(response))
.then(data => this.setup(data));
where safetyParseJSON is:
safelyParseJSON(response) {
var parsed
try {
parsed = response.json();
} catch (e) {
}
return parsed
}
but i keep receiving this error:
"uncaught (in promise) SyntaxError: Unexpected end of JSON input"
Anyone have any idea on what am i doing wrong?
Note:
I am receiving this error only when receiving 404 / 500 from the server, if the results are ok, this works.
Note2: that i am wrapping this function inside try-catch but this still doesn't work, it doesn't catch the exception.
Note3: I have tried to replace this line:
parsed = response.json();
with this line:
parsed = JSON.parse(response);
But than the response is always undefined.
check the response's status prior to calling .json():
.then(response => {
if (response.ok) {
return response.json().then(data => this.setup(data));
}
return Promise.reject(response.text());
});
I ended up using Jeremy Danyow answer, with a small change:
.then(response => {
if (response.ok && response.status === 200) {
return response.json().then(data => this.setup(data));
}
return Promise.reject(response.text());
});
adding the response.status check was necessary in my case as response.ok was true for status code 204 (No content) aswell.

Categories

Resources