How to get the data associated with the error response back? - express

I am making a request from the front-end to a route in my backend that is validating the token associated with a user, which would send an error response back to the front-end if the token has expired. I am sending some json with it but upon doing console.log of the error message in the catch block, the json sent along the error response is not shown.
Sending the error response like this
res.status(401).json({
message: 'User session has expired'
})
But the response that I am getting in the catch block in the front-end has no sign of the json sent with the error.
POST http://localhost:3001/check-validation 401 (Unauthorized)
Error: Request failed with status code 401
at createError (createError.js:17)
at settle (settle.js:19)
at XMLHttpRequest.handleLoad (xhr.js:78)
I don't understand why the json sent along the error response is not shown and how to get it?

Upon doing console.log of the error only the stacktrace of the error is shown and not the data associated with it. The data sent with it can be procured and depends on how the request has been made or by what library it has been made. If the request is made by axios then the following can be done:
axios.post('/formulas/create', {
name: "",
parts: ""
})
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error.response.data.message)
});
Here, in axios the details of the error would be wrapped up in error.response. Whereas, if the request was made by the fetch API then something following can resolve the problem:
fetch('/401').then(function(response) {
if (response.status === 401) {
return response.json()
}
}).then(function(object) {
console.log(object.message)
})
P.S I was searching a lot regarding this problem but didn't get an answer on SO, neither got any article or docs regarding it, even the official Express docs on error handling were not helpful. At last, I understood that the problem lies with the library that is being used to make the request. That's why answering my own question to mark the presence of this question on SO. A detailed discussion can be found here related to axios and here related to fetch api

Related

Axios triggering weird in React native app

Hello i have a weird thing going on,im using axios in order to send post-get http request for my app.The thing is that axios in my pc working good but in my laptop need console.log("") before axios request i dont know why.This happens in all my files.
It gives me this error : Possible Unhandled Promise Rejection (id : 0 ):
[Axios error: Request failed with statis code 404]
Here is my code :
function getProfile(){
try{
//console.log("") <-------------------------- Here i put it
axios.post(URL+'/checkData',
{
usernameCheckAXIOS : username,
passwordCheckAXIOS : password,
})
.then((response)=>{
console.log(response.data)
setProfile(response.data);
if(response.data.responseOfProfile == false){
Alert.alert("Access Dinied")
}
else{
navigation.navigate('Home')
}
})
}catch(error){}
}
If you are getting a “Possible unhandled promise rejection” warning in your React Native app, it means that a promise was rejected, but the rejection was not handled. Promises in JavaScript are used to handle asynchronous operations, and they can either be resolved or rejected.
axios.post(URL+'/checkData',
{
usernameCheckAXIOS : username,
passwordCheckAXIOS : password,
})
.then((response)=>{
//... your code
})
.chatch(error => console.log(error)) // <-- add this line
The HTTP 404 Not Found response status code indicates that the server cannot find the requested resource
so verify your URL, should be invalid because it cannot be found.
[Axios error: Request failed with statis code 404] is an error URL not found.
Are you sure that the url URL+'/checkData' is valid ?

VueJS POST http://127.0.0.1:8000/login 404 (Not Found)

so i post this qs yesterday enter link description here
i was getting this **Uncaught (in promise) Error: Request failed with status code 405 VUEJS
**
now i did fix the part of axios from this :
axios.post('http://127.0.0.1:8000/?#/login/',{
email: this.email, password: this.password
}, headers)
.then((response)=>{
const data=response.data;
console.log(data);
})
to this
axios({
method: "post",
url: "/api/login/",
data: {
email: "",
password: ""
}
}).then(
response => {
console.log(response);
},
error => {
console.log(error);
}
);
now i'm getting this error
as u can see the problem and the api.php and the root
405 error code means your api endpoint not allow the current method you requesting to so 405 errorbis aboutbendpoint problems, and about 404 response status in axios if server's response have a 4XX status it'll go directlly on catch it should be somthing like this:
axios.post("http://127.0.0.1:8000/api/login/",{data: value,data1: value1})
.then((res)=>console.log(res))
.catch((err)=>{
// 404 will be loged below
console.log(err.response.status)
console.log(err.response)
}
i have never saw somting like this but i think you should ckeck your api server and make sure you entered the currect url and currect port and make sure in your server logic response part you have'nt a type error or somithing im really sorry if it was'nt helpful
p.s. i wrote the code above with my phone im really sorry its may be a little ugly
and if you have some problems with your api server and your not a backend i can fix it(if its django) or i can make a simple one for you to use

AWS Amplify React Native, throwing 403 InvalidSignatureException when passing data to request

We create an API for authenticated identities only. so the only valid user can access it. the API is throwing 403 InvalidSignatureException whenever there is data in the body of any request.
we also tested the API on native Android. it is working fine with that.
our POST request code is the following,
API.post(apiName, path, {body:{key:value}}).then(response => {
consoloe.log(response);
}).catch(error => {
consoloe.log(error);
});
We have followed everything on GitHub and API gateway but not getting proper solution for it.
I also received the InvalidSignatureException.
I can't tell for sure what the issue is with your request, but I solved my problem by looking at the error response and figured out that my region was wrong (us_east_1 instead of us-east-1).
Try the following:
API.post(apiName, path, {body:{key:value}}).then(response => {
console.log(response);
}).catch(error => {
console.log(error.response); // <--
});
In my case the error.response was:
And under data.message the error was described
In my case I was just getting 403 with no message. After 30 mins I realised that my path variable was missing slash.

react-apollo Error: Network error: Unexpected token < in JSON at position 1

I want to send a request to this server via Apollo and get a query :
const client = new ApolloClient({
link: new HttpLink({
uri:'http://mfapat.com/graphql/mfaapp/'}),
cache: new InMemoryCache()
})
const FeedQuery = gql
query{
allFmr{
fmrId,
name,
studio,
bedRm1,
bedRm2,
bedRm3,
bedRm4
}
}
`
But I'm facing this error message:
Unhandled (in react-apollo:Apollo(FMRScreen)) Error: Network error: Unexpected token < in JSON at position 1
at new ApolloError (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:109336:32)
at ObservableQuery.currentResult (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:109447:28)
at GraphQL.dataForChild (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:103192:66)
at GraphQL.render (http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:103243:37)
....
But I can easily open "http://mfapat.com/graphql/mfaapp/" in my browser and get a query. Does anyone know where the problem is?
Right now, Apollo treats everything sent from the server as JSON. However, if there is an error, then your server might be sending HTML to show a basic error page.
To see the error, open your dev tools, and look at the network tab. This shows an example 401 error:
As you can see, if you were to parse this as JSON you would stumble over the first character: < which is where our error message comes from.
Reading the specific error sent enables you to fix the bug.
To fix the general error, configure your server to send JSON on HTTP errors, not HTML code. This should allow Apollo to parse it and display a sensible error page.
EDIT: Also see this discussion - hopefully they will change the default Apollo behavior, or at least provide useful discussion.
Base on #eedrah answer, I managed to resolve this issue by using an error handler middleware to always return erros as JSONs, so that Apollo Client error link can parse the errors.
// On Apollo server
// Error handler
const errorHandler = (err, req, res, next) => {
if (res.headersSent) {
return next(err);
}
const { status } = err;
res.status(status).json(err);
};
app.use(errorHandler);

Error Handling ExpressJS and MongoDB

What is the suggested way of error handling in ExpressJS and Mongoose.
app.get('/', function(req, res) {
Subjects.find({}, function(err, subjects) {
if (err) {
return res.json(err);
}
res.render('list', {subjects: subjects});
});
});
I just returned the error in json. Any suggestions? Thanks
It depends on what that error is, but I would usually redirect via res.redirect to an 'Error' url, with details of the error.
You could test for the details of the error, and re-run a query (dependent on what the error is of course) but usually if the callback is throwing an error, it's terminal, so log it, redirect, and inform the user in a nice way.
(Or of course, return JSON and handle your response client side, with no redirect)
EDIT
As per comment from Paul -
I didn't mean to return the exact details to the user about the error.
Simply "Database error" or something like that would be more appropriate, depending on what the error was.