I would like to do something like the following with express.
let error = {errorCode:"1234"}
res.sendStatus(403, {error: error});
In my frontend javascript I'd like to catch the error and inspect it like so
getData(mydata).then((data)=> {
console.log(data);
).catch((error)=> {
console.log(error.errorCode);
});
for whatever reason this isn't sending back the json to my catch method and I'd like to know why and how I can send json when I send back a 403.
Use this syntax
res.status(403).send({errorCode:"1234"});
// or
res.status(403);
res.send({errorCode:"1234"});
Just in case , I just faced a similar case ... and found this post ... so to access the response body of a nodejs http 4xx-5xx on the client side, you can use the response.data property of the error object ...
for example in the catch block :
(err => console.log(JSON.stringify(err.response.data))
to access an object or data send in a response with a >= 400 http status
like from a nodejs server for example with
return res.status(403).send({data});
At least it worked for me, Hope this will help
Related
Spring REST API is responding with following response:
On successful execution : It returns me a response of Text type.
On unsuccessful execution : It returns me JSON error object.
Front-End Service Class :
private detailsURL = 'http://localhost:8080/register';
constructor(private http:HttpClient){}
register(regisDetails): Observable<any>{
return this.http.post(this.detailsURL,regisDetails);
}
Front-End Component Class:
registerUser(){
this.service.register(this.regisForm.value).subscribe(
success => this.successMessage = success,
error => this.errorMessage = error.error.errorMessage
);
}
In case of error I'm getting the error message I'm supposed to get. But in case of success I'm not getting the successMessage.
Just wanted to know if there's any way to fetch the Text type response on front end. Or else I'll have to change my backend to send response of JSON Type for successful execution as well.
Please help me understand this thing.
You have to set the status for your response. In the controller part you have to mention consumes="application/json" in api request.
You should be doing your changes at the backend and provide the response in Json format response for both the success and backend. That would be the ideal solution.
It is really a bad design to provide a different response than what is expected. You could check the value of the header in request "accept:application/json" and provide response as was expected by the front end
Front End Fix :
However, in the front end you could always use
JSON.parse(success) to convert the text to Json object and use it further as required.
I am making an http request in an api using React Native with Axios, I can get json and parsear it when the callback is 200, however, for example, when I call a method, for example, to register the user and step an email from a user who is already registered, he returns me an error 400 (Bad Request) but he also brings a json with the error message ("user already registered"). I need to get this error message since it is variable in the API and show to the user, but when I try to give it a console.log I get the following error:
json's return is this:
and my call code looks like this:
How to get this json even with return 400 in catch?
Thank you.
inside of your catch Block, the error object also provides you with a response body
//... your request here
.catch(error => {
console.log('response: ', error.response.data);
});
console.log(error) is calling the toString method of the error object which doesn't show you the response body.
error.response.data should give you the right content. Take a look at this part of the axios docs
I have two issues but I believe the second issue will be fixed once the first is fixed (question title).
I am receiving JSON from woocommerce. I can call for this data by using fetch of course on client side and it looks as such in the code:
async componentDidMount() {
const response = await fetch('/products');
const json = await response.json();
this.setState({
data: json,
})
// other code ....
}
When I go on the browser I get this error regarding my json data:
Unhandled Rejection (SyntaxError): Unexpected token < in JSON at position 0
With the following error in the console.log:
index.js:6 GET http://localhost:3000/products 500 (Internal Server Error)
index.js:6 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
Once the webpage is refreshed...this all disappears, everything becomes A-OKAY, why? and how do I go about rectifying this?
My JSON data when consoled and the page refreshed returns an object - no '<' is there. Also I don't know why I get the 500 error shown above? I am learning node.js - so I think this is a server side issue as I had no issues before I split my code to client and server.
help?
What is happening is the data call you do takes time to load the data.
Till then the this.state.data is null. The error
Unexpected token < in JSON at position 0
is because you are trying to process the this.state.data but finds null. You need to make sure you handle what needs to be displayed when data is null.
Also, I think you don't need the await before response.json()
The 500 server error is a server side issue.
To stop this whole refreshing the page issue; I had to fix my server file (node.js of course)
My get request had originally looked like this:
let response;
app.get('/products', (req, res, err) => {
WooCommerce.get('products', function(err, data, res) {
response = res;
});
res.status(200).json(JSON.parse(response));
});
The issue here was that I was calling /products with fetch which url didn't point to anything but another API call, which only got called once I forced it pass the first url call I guess using a page refresh. Forgive my understanding here.
The correct code was calling Woocommerce api first then passing its response to the /product url so I can fetch it in the front end, like so;
let response;
WooCommerce.get('products', function(err, data, res) {
response = res;
app.get('/products', (req, res, err) => {
if (res.status(200)) {
res.status(200).json(JSON.parse(response));
} else {
console.log('theres an error', err);
}
})
});
And Tarrrrdaaa no refresh issue/SyntaxError error!!!
As one of the answers says, this error happens when you try to parse a nullish value. You can fix this issue by making sure the data is defined before trying to parse it:
if(data){
JSON.parse(data);
}
After a successful creation of new item in my database I send:
res.status(201).json({message:"Successfully Registered"});
On my angular front end I am able to console.log(res) and receive:
{message: "Successfully Registered"}
1) How do I get the status code on the front end? res.status returns undefined. The only response I'm getting is the JSON.
2) What would be the best way to confirm successful desired api calls? For example, when I log in and credentials are correct, should I check for a 200 and then proceed? Or send a custom JSON message and check if the message for example says "Successful login" then proceed?
A little bit late, but another option is to include the status in the JSON object:
res.status(201).json({message: "Successfully Registered", status: 201})
Now you can check the status in the front end doing res.status and use this to proceed with another action.
1- You can do res.status(200).send("You message here");
2- I would say your best option when doing the login and authenticating credentials is to create a session as such
req.session.user = req.body.username //username is the name attribute of the textfield
and then redirect to any page you'd like/you can also set status to 200
res.status(200);
I'm not familiar with Angular, but looking at the docs:
See https://angular.io/api/http/Response
You'll need to do something like:
http
.request('example.com')
.subscribe(response => console.log(response.status));
Sure, checking for 200 is fine. Typically with a REST API (inferred from what you've shown), after a login you're given back a JWT along with 200 OK. And any subsequent API all with that JWT will also yield a 200 OK along with the response body which is usually JSON.
You should tell your angular http client that you want to get the response status. By default, angular deserialize the response body, but you can set request option.observe:'response' to do so.
postData(model: MyModel): Observable<HttpResponse<{status: string}>> {
return this.http.post<{status: string}>(
model, { observe: 'response' });
}
See https://angular.io/guide/http#reading-the-full-response for details.
PS: sending a { status: 'message' } is not very useful, you may return an { id } or even nothing.
res.status(200).json({
status: 'success',
results: tours.length,
data:{
tour:tours
}
});
Usually, Jsend is a good choice to response, and also by convention. Absolutely you can see the 'status' in response data and the actually data you want in the data.
according to the angular guide, we can add observe in the options of our request.
getforgetpassword(email: string): Observable<any> {
const url = this.gatewayUrl + `newPasswordFor/${email}`;
return this.http.get(url, {observe: "response"});
}
using observe type as response will give total response along with request status, which you can use in your logic of controller.
I'm new to Grails and I'm stuck up with a problem. I want to know if there is a way to send both JSON and view and model through "render" in Grails.
I'm using a jQuery Datatable to display data returned from server which is read from JSON returned by the controller. I also need to display error messages on the same view in case of validation failure in form fields. But I'm able to return either only the JSON or model and view using render. I also tried sending the JSON through model itself but it didn't work.
This is my code:-
def hierarchyBreakInstance = new HierarchyBreak(params);
String json = "{\"sEcho\":\"1\",\"iTotalRecords\":0,\"iTotalDisplayRecords\":0,\"aaData\":[]}";
hierarchyBreakInstance.errors.reject(message(code: 'hierarchyBreak.error.division.blank'));
render(view: "hierarchyBreak", model: [hierarchyBreakInstance: hierarchyBreakInstance]);
//render json;
The gsp code:-
<g:hasErrors bean="${hierarchyBreakInstance}">
<div class="errorMessage" role="alert">
<g:eachError bean="${hierarchyBreakInstance}" var="error">
<g:if test="${error in org.springframework.validation.FieldError}" > data-field-id="${error.field}"</g:if>
<g:message error="${error}"/>
</g:eachError>
</div>
</g:hasErrors>
Could you please let me know if there is a way to do this. Thanks!
You can use like this.
def hierarchyBreakInstance = new HierarchyBreak(params);
String json = "{\"sEcho\":\"1\",\"iTotalRecords\":0,\"iTotalDisplayRecords\":0,\"aaData\":[]}";
hierarchyBreakInstance.errors.reject(message(code: 'hierarchyBreak.error.division.blank'));
render(view: "hierarchyBreak", model: [hierarchyBreakInstance: hierarchyBreakInstance,json:json]);
//render json;
Assuming that you are doing a request with some parameters, and need to return if was succesfull or not, and the data to fill the table with ajax.
I will do on that way, use the statuses of the HTTP to mark if it was a problem with the validation(normally we return 400 Bad Request and the message)
Example :
return ErrorSender.sendBadRequest("error validating field $field with value $value")
And the errorsender has a sendBadRequest method
[response: ['message': message, error: "bad_request", status: 400, cause: []], status: 400]
If the request was OK, you only need to respond the data with something like
return [response: results, status: 200]
In the client side you have to have one function if the request was OK to parse result, and one function if request have some validated data problem, database problem or whatever that caused that the request didnĀ“t return a 200(in the example),there are more status codes, you can check on
http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
PD: Initial validation should be done on client side.