I'm using angularjs with wildfly v8.2. I have a problem when try to pass multiple params in services in angularjs using get rest services. I've got this error : "Bad arguments passed to org.jboss.resteasy.spi.metadata.ResourceMethod#7a3ab29a" ( null, java.lang.Integer 1 ). How do i pass multiple parameter using get in angularjs. Anyone..
Below is my codes:
services.js
authListing: function (id, page, succFn) {
return $http.get(services.path + 'student/listing', {params: {page: page, id: id}}).success(succFn).error(cmnSvc.errorHandler);
}
rest.java //endpoint
#Path("/listing")
#GET
public Response listing(#QueryParam("id") String id, #QueryParam("page") int page) {
//Some method here
}
You are making the call with Angular correctly. However, I suspect you are passing in either a null or undefined argument based on the error message:
"Bad arguments passed to
org.jboss.resteasy.spi.metadata.ResourceMethod#7a3ab29a" ( null,
java.lang.Integer 1 )
My guess is that your endpoint isn't meant to take a null value for id and that is why it is puking.
You should be able to figure this out pretty quickly by simply opening up the developer tools in your browser, and inspecting the XHR request made to the server.
If it looks something like this: student/listing?id=undefined&page=1 then you know you have a problem.
Related
I would like to setup axios to delete a record using a resource route:
axios.delete('/job-management', this.deletedata).then((res)=>{
console.log(res);
})
For my routes I have:
Route::resource('job-management', "PositionsController", [ 'as' => 'jobs']);
Now, in my PositionsController I have:
public function destroy(Positions $positions) {
return $positions;
}
But the above always returns "method not allowed". How can I handle a delete request with the axios delete() method?
Laravel throws the MethodNotAllowedHttpException when we attempt to send a request to a route using an HTTP verb that the route doesn't support. In the case of this question, we see this error because the JavaScript code sends a DELETE request to a URL with the path of /job‑management, which is handled by a route that only supports GET and POST requests. We need to change the URL to the conventional format Laravel expects for resourceful controllers.
The error is confusing because it hides the fact that we're sending the request to the wrong URL. To understand why, let's take a look at the routes created by Route::resource() (from the documentation):
Verb URI Action Route Name
GET /job-management index job-management.index
GET /job-management/create create job-management.create
POST /job-management store job-management.store
GET /job-management/{position} show job-management.show
GET /job-management/{position}/edit edit job-management.edit
PUT/PATCH /job-management/{position} update job-management.update
DELETE /job-management/{position} destroy job-management.destroy
As shown above, URLs with a path component of /job-management are passed to the controller's index() and store() methods which don't handle DELETE requests. This is why we see the exception.
To perform a DELETE request as shown in the question, we need to send the request to a URL with a path like /job-management/{position}, where {position} is the ID of the position model we want to delete. The JavaScript code might look something like:
axios.delete('/job-management/5', this.deletedata).then((res) => { ... })
I've hardcoded the position ID into the URL to clearly illustrate the concept. However, we likely want to use a variable for the this ID:
let positionId = // get the position ID somehow
axios.delete(`/job-management/${positionId}`, this.deletedata).then((res) => { ... })
The URL in this form enables Laravel to route the DELETE request to the controller's destroy() method. The example above uses ES6 template string literals because the code in the question suggests that we're using a version of JavaScript that supports this feature. Note the placement of backticks (`) around the template string instead of standard quotation marks.
as I can see in your code above, you pass Positionseloquent as a parameter to destroy method but in your vueJS you don't pass this object. for that you would pass it like this :
axios.delete('/job-management/${id}').then((res)=>{
console.log(res);
})
and the id param inside the url of ur axios delete, it can object of data or any think.
i hope this help you
I'm experimenting with Zendesk apps but I'm having an issue passing variables / an array of json objects from my app into the view. I did the getting started tutorials and looked at the API but I can't seem to find an answer.
Here is what I have:
this.ajax('fetchExternalData', myURL).done(function(data) {
this.switchTo('requester', data);
});
but whenever I try to access data in the app, it says it's undefined (data is an array of objects here).
I even tried something like:
this.ajax('fetchExternalData', myURL).done(function(x) {
this.switchTo('requester', x);
});
Where x is just some plain text.
if I do:
this.ajax('fetchExternalData', myURL).done(function(data) {
data = data[0];
this.switchTo('requester', data);
});
I can access properties in data by their name (eg. {{CustomerName}}) but I still can't reference the data var itself.
According the Zendesk site :
this.switchTo('hello', {username: currentUser});
The first argument specifies the template to render, hello, which references the hello.hdbs file in the templates folder. The second argument specifies the data to pass to the template, expressed as a JavaScript object literal, {username: currentUser}. The current user's name is passed to the template to be displayed in the user interface.
So just try like that :
this.ajax('fetchExternalData', myURL).done(function(data) {
//this.switchTo('requester', data);
this.switchTo('requester', {data : data} );
});
I hope this will resolve your issue !
I'm having an issue getting Ember.js with Ember Data to hit a nested resource API endpoint. Here is my code:
https://gist.github.com/feliksg/7470254
Here is what i'm using:
DEBUG: ------------------------------- ember.js:3224
DEBUG: Ember : 1.2.0-beta.3 ember.js:3224
DEBUG: Ember Data : 1.0.0-beta.2 ember.js:3224
DEBUG: Handlebars : 1.0.0 ember.js:3224
DEBUG: jQuery : 2.0.3 ember.js:3224
DEBUG: -------------------------------
I'm also using Ember Appkit as the base for this project.
Basically the issue is when I try to submit a new post, ember data does the following:
POST request to /user/posts
instead of a
POST request to /users/1/posts
In addition, for some reason the request payload as shown by chrome inspector shows the form data being passed to the API looks like this:
{ "user/post": { "published":false, "created_at":null, "user":"1" } }
However, I would expect the data to be passed in like this:
{"post": { "body":"some text...", "published":false, "created_at":null, "user_id":"1" } }
So for some reason, it doesn't even pass in the 'body' field even though I have it in the form.
Any help is greatly appreciated!
UPDATE 1
When I visit http://localhost:8000/#/users/1/posts, it sends a GET API request to /users.json. There must be something wrong with the way I set up the PostsRoute but i'm not sure how to fix it.
UPDATE 2
I've updated my PostsRoute to fetch the JSON without using Ember Data which returns the records, but now the posts template does not render. My PostsRoute now looks like this:
PostsRoute = Ember.Route.extend
model: (params) ->
user = #modelFor('user')
userId = user.get('id')
return $.getJSON('http://localhost:5000/api/v1/users/' + userId + '/posts.json')
I also get the following error:
Error while loading route: TypeError: Object # has no method 'slice'
So when you create/use 'users/post' you are defining a namespace where the post lives, not that it's underneath a specific model. AKA, it isn't going to use the associated user model to build up your url, it's just going to make requests using users as part of the post.
I'm not totally positive why the body isn't being attached to the post, are you sure the model includes the body? Are you sure the body property exists on the model you are sending into the createRecord?
BTW, needs doesn't do anything on a route, it only applies to controllers.
I have a AngularJS webapplication with a Jersey Backend Application.
Now everything is working fine using ngResource to access REST resource out of AngularJS. The only problem is with the DELETE option.
I have the following code to delete a course using my ngResource:
Course.deleteCourse = function(course) {
course.$remove({
courseId:course.id
});
return course;
};
In the backend (Jersey) I have the following code:
#DELETE
#Path("{id}")
public final void remove(#PathParam("id") final String id) {
System.out.println("DELETE ID = " + id);
}
If I try to delete an item the following url is called from Angular:
DELETE http://localhost:8080/manager-api/courses/5
This is fine (after me). If I call this url from CURL, i get the ssystem.out from the Backend posted to the console.
In the client-app (AngularJS) i get the following exception on the browser console:
DELETE http://localhost:8080/manager-api/courses/5 415 (Unsupported Media Type)
Anyone an idea what the problem might be? POST + GET are working fine.
I have the following consume/produce annotations:
#Consumes({ MediaType.APPLICATION_JSON })
#Produces({ MediaType.APPLICATION_JSON })
Thanks in advance for your help.
Greets
Marc
EDIT:
I have tried to replace the way of accessing the REST services out of AngularJS with $http.
Now my service looks as below:
MyApp.factory("Course", ["$http", function ($http) {
var courseBaseUrl = "/api/courses/";
return {
show: function show(courseId) {
return $http.get(courseBaseUrl + courseId);
},
list: function list() {
return $http.get(courseBaseUrl, {});
},
remove: function remove(courseId) {
return $http.delete(courseBaseUrl + courseId, {});
},
save: function save(course) {
return $http.post(courseBaseUrl, course, {});
}
};
}]);
The result is still the same. The application calls e.g
DELETE http://localhost:8080/manager-api/courses/1
and receives a
DELETE http://localhost:8080/manager-api/courses/1 415 (Unsupported Media Type)
If I call the same DELETE call on Curl, everything works fine.
Thanks for your help
Marc
I came across this as well, the problem is angular always sets the Content-Type header to xml on DELETE requests and jersey will chuck an error as you have specified that your api consumes/produces JSON with the annotations.
So to fix it (from the client side), set the content-type header, eg:
.config(function($httpProvider) {
/**
* make delete type json
*/
$httpProvider.defaults.headers["delete"] = {
'Content-Type': 'application/json;charset=utf-8'
};
})
However, for reasons I dont understand/dont know of, angular will strip away the content-type header from the request if it has no data. This would make sense if it wasn't for the fact that browsers (chrome at least) will always send a content-type... Anyway you will have to go to the trouble of finding this in the angular source:
// strip content-type if data is undefined
if (isUndefined(config.data)) {
delete reqHeaders['Content-Type'];
}
and get rid of it. I dont know of a way to do this without editing the source. Maybe someone with better JS know-how, erm, knows how.
Alternatively, from the server side, you can do as Rob has suggested and change the Jersey configuration to allow consuming MediaType.APPLICATION_XML
#Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public final void remove(#PathParam("id") final String id) {
System.out.println("DELETE ID = " + id);
}
I had same issue, Try returning new instance of Course object in your delete method.
#DELETE
#Path("{id}")
public final Course remove(#PathParam("id") final String id) {
System.out.println("DELETE ID = " + id);
return new Course();
}
Using angularjs $resource (instead of $http), without "payload" in the request, the content-type is setted as text/plain.
So IMHO it's better a server side support.
"Postel's Law states that you should be liberal in what you accept and conservative in what you send. -- source"
#DELETE
#Path("{id}")
#Consumes({ MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN })
public void remove(#PathParam("id") Long id) { ...
I have a project that uses PageMethods to call functions on the server.
The server functions (written in C#) return the values as array of strings, without doing any kind of serialization and in the client side (from Js) the accessing of the return values is by using static variable called arguments.
I found that sometimes for some users (cases are not repro) sometimes an exception occured
"WebServiceFailedException the server method 'Foo' returned invalid data.
the 'd' property is missing from JSON."
Some searching on google I found that people are serializing the return values using DataContractJsonSerializer class and in js accessing the return value using one of the callback function
Example:
function OnRequestComplete(result,
userContext, methodName) {
var Person = eval('(' + result + ')');
alert(Person.Forename);
alert(Person.Surname); }
So is the first technique is correct? or what?
P.S:
the function on the server is defined on the default.aspx.cs file as follows:
[System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
public static string[] Foo(string s);
from the client side the calling is as follows
PageMethods.Foo("value",OnSuccess);
Also all the users have the same browser version (IE8)
I don't know if it's the entire problem, but your first issue is manually serializing the return value. PageMethods and ScriptServices automatically JSON serialize their return values. Nesting two levels of JSON could definitely be throwing a wrench in the framework's client-side deserialization process (which is also happening automatically, before your eval() code).
To return an instance of your Person class, this is all you need:
public static Person GetPerson() {
Person p = new Person();
// Populate the Person object here.
return p;
}
Then, on the client-side you can work with the object's properties as expected:
function OnRequestComplete(result, userContext, methodName) {
console.log('Person name: ' + result.Forename + ' ' + result.Surname);
}
Alternatively, if you're using jQuery for other tasks and already have it on the page, you don't even need the ScriptManager and MS AJAX to call page methods. You can directly call page methods with jQuery and skip all that overhead.
Without knowing how the request is made and how the server end is coded, my answer may not be accurate.
Where is the WebMethod decorated method in your server side code? If it is an a separate class with the ScriptService attribute, and if JSON is specified while making the request, then the JSON values should have been automatically serialized and dont need to be serialized manually again. With this set up ASP.NET 3.5 wraps the response in a "d" object
Some users getting the exception might be due to the browser that they are using. If you are using jQuery, I'd specify the content type as so in the ajax request body
contentType: "application/json; charset=utf-8",
Hakeem
This is a bit funky. ASP.NET always adds the "d" to all results. So it either should work or not. Here is some background on the "d" issue:
http://encosia.com/2009/06/29/never-worry-about-asp-net-ajaxs-d-again/