Error message not passed in Amplify.js request - amplifyjs

I have this code that uses amplify.js:
amplify.request.define('data', 'ajax', {
url: "WebService.asmx/HelloWorld",
datatype: "json",
type: "POST"
});
amplify.request({
resourceId: 'data',
success: function(p1, p2, p3) {
debugger;
},
error: function(p1, p2, p3) {
debugger;
}
});
The problem is that is server reports error, then the in the error callback, the p1 is null, p2 is 'error' and p3 is undefined.
The similar jQuery.ajax fills these parameters correctly.
$.ajax({
type: "POST",
url: "WebService.asmx/HelloWorld",
success: function(p1, p2, p3) {
debugger;
},
error: function(p1, p2, p3) {
debugger;
}
});
Am I missing Amplify.js configuration to make this work?

Following this link
Amplify Support Group
looks like parsing error body is not supported by default. I will have to write my own decoder for this.

By default amplify is using Jsend decoder that you can replace with your own.
Here's my simple decoder that passes response body JSON object to both success and error callbacks:
amplify.request.decoders._default = function( data, status, ampXHR, success, error ) {
if (status === "success") {
success(data);
} else {
error(JSON.parse(ampXHR.responseText));
}
}
PS. Before doing it, consider adjusting your api responses to the jsend conventions, read more here: http://labs.omniti.com/labs/jsend

Related

React useQuery - useMutation onError not catching

I'm using a combination of Axios and react-query to make a POST request to a server that may answer with response code 400 and validation errors.
export const axiosDefault = axios.create({
baseURL: API_LINK,
headers: {
'Content-Type': 'application/json'
},
})
const contactMutation = useMutation(
(data) => axiosDefault.post('/contact', data),
{
onSuccess: (response) => {
console.log('Success', response)
},
onError: (error) => {
console.log('Error', error)
}
}
)
However, when calling contactMutation.mutate(someData) the error response from the server does not get processed by the react query library and instead propagates upward. Neither the onSuccess or onError handlers get called, the isError property of the mutation is also not set.
I've spent hours tearing my hair out over this, what am I doing wrong?
hi i also had same issue i solved by wrapping api function to try/catch block and throw the catched Error.
(data) => {
try {
axiosDefault.post('/contact', data),
} catch (error) {
throw error
}
}

axios DELETE request with body in Nuxt.js

I have an app built with Nuxt.js. To get data from the API I use axios, namely #nuxtjs/axios. All request work fine but for the DELETE method.
My syntax is the following:
async removeItemFromCart(productId) {
const accessKey = await this.$store.dispatch('fetchUserAccessKey');
try {
this.$axios.delete(`/api/baskets/products?userAccessKey=${ accessKey }`, {
data: {
productId: productId
}
})
} catch (error) {
console.log(error);
}
},
However, in the console I always get the following error: createError.js?2d83:16 Uncaught (in promise) Error: Request failed with status code 400
I tried to use params instead of data, but to no avail. What am I missing here?
It seems that there's an issue with axios: when you use delete method with body, it either doesn't include payload, or deletes Content-type: 'application/json' from headers. To solve the issue, I used .request instead of .delete (according to https://github.com/nuxt-community/axios-module/issues/419)
this.$axios.request(`/api/baskets/products?userAccessKey=${ accessKey }`, {
data: {
productId: productId
},
method: 'delete'
}).

Angularjs ngResource needs to have file as one of the fields

I have resource that has following fields:
description, picture
Is it possible to send that resource to URL as multipart/form, and if so, how?
I've tried putting:
app.factory('resource_name', ['$resource', function($resource) {
return $resource('<url> ',
{
<params_for_url>
},
save: {
method: "POST",
headers: {
"Content-Type": "multipart/form-data;"
}
},
but this doesn't get to the server as form-data. It goes like JSON with header just set:
{
description: "gtrdgf",
picture: {
lastModifiedDate:2013-11-26T20:42:13.000Z,
name: "suggested_pokes.png"
size: 32995
type: "image/png"
webkitRelativePath: ""
}
Did anyone met this requirement before? If this is possible at all...
Thanks!
I found solution for this one. You have to use FormData to submit it. You can use it as interceptor. I used it like this (this is my save method of ngResource)
save: {
method: 'POST',
transformRequest: formDataObject,
headers: {'Content-Type':undefined, enctype:'multipart/form-data'}
},
and here is transformer:
function formDataObject (data) {
var fd = new FormData();
angular.forEach(data, function(value, key) {
fd.append(key, value);
});
return fd;
}

SyntaxError: missing ; before statement in kendoui

how come when i'm clicking on the update button popup kendo grid , this error ocurrs?
The error in Firefox browser is in this form : SyntaxError: missing ; before d.0=value
and in Chrome browser : Uncaught SyntaxError: Unexpected number
I've uploaded a video regarding this error for elaboration n stuff
Jsfiddle Code
Video
Code
transport: {
read: {
url: 'https://dl.dropboxusercontent.com/sh/u9oxg5f6uweqh40/CbR3pNVg04/documentj',
dataType: 'json',
type: 'get',
cache: false
},
update: function(e) { return true; }
}
save: function (e) {
var that = this;
$.ajax({
url: '/echo/json',
type: e.model.id == null ? 'POST' : 'PUT',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(e.model),
success: function (data) {
// Alertify.log.success(data);
console.log('ok dadasaved');
that.refresh();
},
error: function (data) {
// Alertify.log.error(data);
console.log('no datasaved');
that.cancelRow();
}
});
}
You should provide more code to detect what's wrong with your code, but read this may help you:
Such error occurs when the transport definitions are inconsistent. In other words, if you would like to use custom transport method, all transport types should be defined as functions.
Having a standard read transport and custom update is not supported. Please configure all transports as functions and let me know if the error still occurs.
I had the same error and for me the problem was that the dataType option was not set for all transport methods. I marked that line with a comment below:
var linksDataSource = new kendo.data.DataSource({
transport: {
read: {
dataType: "json",
url: 'read-url',
type: "get"
},
destroy: {
dataType: "json", /* <============ THIS LINE WAS MISSING */
url: 'delete-url',
type: "delete"
},
update: {
dataType: "json",
url: 'update-url',
type: "post"
},
create: {
dataType: "json",
url: 'create-url',
type: "post",
complete: function () {
$("#searchResult").data("kendoGrid").dataSource.read();
}
},
/* ... */

making jquery AJAX POST to resful API

I'm trying to convert a REST call using Cordova plugin to a JQuery AJAX POST. I don't have the JQuery code right, the call is getting a connection refused error (hitting localhost). I'm successfully making GET requests to my localhost, so there isn't a connectivity issue.
The REST API code:
#Path("/track")
public class TrackResource {
...
The method in TrackResource class i'm trying to hit :
#POST
#Path("{trackid}")
#Consumes("application/json")
#Produces("application/json")
public Response addToResource(#PathParam("trackid") String trackid, String bodyJson) {
The AJAX code:
var trackingJSON = JSON.stringify(tracking_data);
var urlAjax = "http://localhost:7001/ds/resources/track/" + trackid;
$.ajax({
type: "POST",
url: urlAjax,
data: trackingJSON,
beforeSend: function() { $.mobile.showPageLoadingMsg("b", "Loading...", true) },
complete: function() { $.mobile.hidePageLoadingMsg() },
success: function(data) { alert("ajax worked"); },
error: function(data) {alert("ajax error"); },
dataType: 'json'
});
I'm not sure if i'm using the data option in the ajax call correctly, but it's my understanding that is where you would put the data you want to pass server side.
I do have other GET calls to this same TrackResource class working, so i know the base part of the URL is correct. I know the trackid value is populated correctly as well.
If you're posting a JSON string make sure you also set contentType: "application/json".
var trackingJSON = JSON.stringify(tracking_data);
var urlAjax = "http://localhost:7001/ds/resources/track/" + trackid;
$.ajax({
type: "POST",
url: urlAjax,
contentType: "application/json",
data: trackingJSON,
beforeSend: function() { $.mobile.showPageLoadingMsg("b", "Loading...", true) },
complete: function() { $.mobile.hidePageLoadingMsg() },
success: function(data) { alert("ajax worked"); },
error: function(data) {alert("ajax error"); },
dataType: 'json'
});
I needed to use the router address of my computer, 192...., in order to hit my localhost... I was running the application on an actual Android device, however, I guess trying to use localhost or 127.0.0.1 in the AJAX call must have been causing issues.