I'm using the new (4.3) HttpClient in angular to POST data to my backend server:
this.httpClient.post<View>(`/path`, data).subscribe(
(view: View) => console.log("Success"),
(error: HttpErrorResponse) => {
console.log(error)
this.errorMessage = <any>error.error;
});
);
This call generates an (expected) error (409), but for some reason, the logged error does not contain the body of the error sent from the server. I can see the status code, but the error.error field, which should contain the response body is missing. Anyone have any ideas what could be wrong?
I've tested the backend call using curl, and can see the response body from the server.
Is your error body coming back as JSON or un-formatted text/other? I had a similar problem until i realized the body returned with the error result was a simple string. I had to change the call to something similar to this (forgive the lack of type-safety here):
this.http.post('http://address', body, { responseType: 'text' })
.subscribe(data => {
this.result = data['value'];
this.router.navigate(['/route']);
}, (error: HttpErrorResponse) => {
this.error = error.error;
this.router.navigate(['/error']);
});
This is a known bug in angular which is throwing an exception during the json parsing and not populating the error field:
https://github.com/angular/angular/pull/18466
Related
If I do this in my Vue.js script component
getResumeAPIData(id){
// declare a response interceptor
axios.interceptors.response.use((response) => {
// do something with the response data
console.log('Response was received');
return response;
}, error => {
// handle the response error
return Promise.reject(error);
});
// sent a GET request
axios.get(`api/resume-data-returns/${id}`)
.then((response)=>{
this.RelationTable = response.data
console.log(this.RelationTable);
})
},
I get a response like this
{"id":1,"name":"userlocalvm","email":"userlocalvm#v","email_verified_at":null,"type":"user","bio":"Why","photo":"1606931001.jpeg","created_at":"2020-12-02T16:01:00.000000Z","updated_at":"2020-12-02T17:43:21.000000Z"}
Because of my Laravel api.php->Controller Backend code
$findOrFailId = Resumes::findOrFail($forEachId);
$foreignKeyOfResTable = $findOrFailId->user_id;
return User::findOrFail($foreignKeyOfResTable);
But if I do it like this as
// sent a GET request
axios.get(`api/resume-data-returns/${id}`)
.then((response)=>{
this.RelationTable = response.data.created_at
console.log(this.RelationTable);
})
The added dot then the property name of the column
response.data.created_at
I get a response
undefined
Sorry if this is a silly question as I am still quite a rookie in programming in general and the jargons that comes with it and I want learn and master javascript and php so bad!
It might be that the response is inside another data object. You might have to do something like this:
response.data.data.created_at
I've got a Laravel Lumen 7 RESTful API alongside a Nuxt JS front-end with Axios. My front-end makes Axios calls to the API and inside of my Lumen project I'm of course returning relevant responses and error codes. However, it appears that these responses although I can see them when I inspect the network and can see it in the preview/response tabs, I'm unable to access it from Axios in my catch() block...
If I change it to a 200 response then I can access it from my then() block but this isn't ideal.
Lumen response
return response()->json(['success' => false, 'message' => 'We\'re unable to add this domain right now, please try again shortly'], 500);
JS Axios function
/*
** Add domain
*/
addDomain () {
// add new domain
this.$axios.post(`${process.env.API_URL}/api/domains/add`, this.domainCreation).then(res => {
console.log(res)
}).catch(err => {
console.log(err) // doesn't display my Object from laravel, instead just the native error string: "Error: Request failed with status code 500"
})
}
Can anyone help?
try this err.response catch error data is inside response
this.$axios.post(`${process.env.API_URL}/api/domains/add`, this.domainCreation).then(res => {
console.log(res)
}).catch(err => {
console.log(err.response);
})
ref link https://github.com/axios/axios#handling-errors
In addition to the above answer, you should consider returning the correct response codes.
5xx error codes are for Internal Server Errors. You are probably looking to return a 422 unprocessable entity error.
More info about 500 status code: https://httpstatuses.com/500
More info about 422 status code: https://httpstatuses.com/422
I have a little problem with DingoAPI and Vue.js when I'm trying to get my error message from response. I think the browser is replacing my custom message by the default one. Here is my code:
PHP script
if($request->readerId){
Return succes (this works properly)
else{
return $this->response->error(
'No reader',
400 //(or diffrent code)
);
}
Vue.js script
await axios.post(API_URL + 'card/', {
some data
}, {
headers: {
headers
},
}).then(({data}) => {
context.commit(SET_RESPONSE, data);
}).catch((error) => {
console.log(error.message);
throw error
})
When I'm trying to look on my message in the network tab I can see (so DingoAPI did it correctly):
{"message":"No reader","status_code":400}
But when I'm using console.log(error.message) or trying to show it on the page there is standard error message:
Request failed with status code 400
Is there a way to set error message with DingoAPI and catch it in my .js script?
Maybe I need to write my own custom exception?
What you want is access to the data of the response from your error variable.
console.log(error.response.data.message); // No reader
Otherwise you can log error.response to see the object:
console.log(error.response);
If you wonder why it's printing Request failed with status code 400:
The problem is when the console.log tries to output the error, the string representation is printed, not the object structure, so you do not see the .response property.
Source: https://github.com/axios/axios/issues/960#issuecomment-309287911
I send a request to a remote API. It takes a little time for API to proceed on its side.
After this little waiting time, i can see in network tab a HTTP 200. In the response, I got the proper intended information. Everything on the API side works fine.
BIT on the console, I can see I encountered a XMLHttpRequest Error.
Why, especially if I have a XMLHttpRequest Error, the POST is completed with 200? Shouldn't it be "blocked" by Angular2?
The unintended result is: my file is correctly uploaded and handled by the API, but in Angular2, it triggers the ERROR part of my call.
If I use https://resttesttest.com/ for example, it seems to encounter the same error but it doesn't finalize the POST:
Oh no! Javascript returned an
HTTP 0 error. One common reason this might happen is that you
requested a cross-domain resource from a server that did not include
the appropriate CORS headers in the response.
Angular 2 Code for this call
this.http
.post(this.documentUploadAPIUrl, formData, options)
.subscribe(
res => {
this.responseData = res.json();
console.log(this.responseData);
console.log('Uploaded a blob or file!');
},
error => {
console.log('Upload failed! Error:', error);
}
);
try to set withCredential attribute of xmlHttpRequest to true, this will send credentials managed by the browser, in angular 2 you can do like this
import { RequestOptions } from '#angular/http';
this.http
.post(this.documentUploadAPIUrl, formData, this.post_options)
.subscribe(
res => {
this.responseData = res.json();
console.log(this.responseData);
console.log('Uploaded a blob or file!');
},
error => {
console.log('Upload failed! Error:', error);
}
);
post_options() {
return new RequestOptions({ method: 'post', withCredentials : true });
}
I'm creating app using angular2 and i need to get weather from yahoo weather. I try to do it using http get method but it's give me a error.
import {Component,OnInit,} from "angular2/core";
import {Http} from "angular2/http";
import 'rxjs/add/operator/map';
#Component({
templateUrl:'app/contact/contact.html',
})
export class ContactComponent{
constructor (private http: Http) {}
public url:string= "http://weather.yahooapis.com/forecastjson?w=2295424";
ngOnInit(url:string) {
return this.http.get(url).map(res => {
return res.json();
}).subscribe((response) => { console.log(response) });
}
}
Error I get is
EXCEPTION: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
can anyone help me with this?.
You need to append Accept headers to your get request in order for Firefox to render the json that comes back. I found this after searching quite a bit and came across this https://brockallen.com/2012/04/27/change-firefoxs-default-accept-header-to-prefer-json-over-xml/ which led me down the path of adding the headers
ngOnInit() {
let headers = new Headers();
headers.append('Accept', 'q=0.8;application/json;q=0.9');
return this.http.get(this.url, { headers: headers } ).map(res => {
return res.json();
}).subscribe((response) => { console.log(response) });
}
I think the payload of your response isn't actually JSON. That's why Angular can't parse it. You could have a look within the Network tab of the Chrome developer tools for example for more hints.
I try your request (http://weather.yahooapis.com/forecastjson?w=2295424) and I got a 404 response with an HTML payload (and not a JSON one).
A strange thing in your code is the parameter you provide to the ngOnInit method. You should try something like that:
ngOnInit() {
return this.http.get(this.url).map(res => {
return res.json();
}).subscribe((response) => { console.log(response) });
}
Hope it helps you,
Thierry