Ember-data resolves wrong API endpoint - javascript

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.

Related

Laravel resource route delete from axios

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

pass multiple params in services in angularjs

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.

Ember Transion-to URL not working

I have an ember action that submits a form using jquery post like this,
submit : function(){ //submitting new story
this.set('onsubmit' , true);
var self = this;
$.post( "/api/post", { some post data })
.done(function(data) {
self.transitionTo('post' + data);
});
}
The urls are like this, domain example.com. Post is located at example.com/api/post. After posting the user must be redirected to example.com/post/3432232 (some value returned by the post data).
However after posting this transition to "example.com/api/post/5000203" not example.com/post/234234234.
Which doesnt exists and gives a 404. How can I make the user go back to example.com/post/234234234 using transition-to function in ember?
Edit - Routes are as follows
App.Router.map(function() {
this.resource('index', {path : '/'} , function() {
this.resource('p', function(){
this.resource('post', { path: ':post_id' });
});
});
});
Thanks
In Ember routing system transitionTo takes as arguments route's name and route's model (the same model, that route returns when Ember.Route.model hook is invoked). There are two type of router's transitions in Ember's glossary: URL transition (happens when client handles new URL, fo ex., when you open a page from scratch) and "named transition" (which happens when this.tranisionTo is called).
Ember.Route tries to load model based on params list (:post_id, for example) while handling "URL transition". In other hand, while it handling "named transition" it doesn't call model hook, but uses already provided model (this.tranisition('post', PostModel)`). Docs.
So, if you have post_id on hands, just call this.store.find('post', postId) to get PostModel and provide requested model to PostRoute: this.transitionTo('post', this.store.find('post', data).
P.S. Please, consider reading this question and an answer to get your routing structure actually nested: Nested URLs: issues with route transition.
P.P.S. I looked at the Ember's documentation and found new (at least for me) signatures for transitionTo method: http://emberjs.com/api/classes/Ember.Route.html#method_transitionTo. According to this doc, you can rewrite your example to get it work: this.tranisitionTo('post', data), where data is post_id.

Meteor - client can't get the collection

I'm still trying to get my head around the whole publish/subscribe aspect of Meteor.
This is the gist of what I'm trying to achieve.
On server side, at "Meteor.startup", I grab RSS feeds from a blog. This part works. Basically, my server code looks like
Items = new Meteor.Collection "items"
Meteor.startup ->
..
.. # code for fetching the RSS feeds
..
for each feed
Items.insert
title:item.title
console.log Items.find().count() # this returns the correct count
Meteor.publish "items", ->
Items.find()
Now that I have published the "items", I want to subscribe to it from the client.
Items = new Meteor.Collection "items"
Meteor.subscribe("items")
console.log Items.find().count()
But above gives me "0".
What am I doing wrong?
Subsribing is asynchronous, you need to wait for the subscription to be completed by passing a callback function before trying to access the data in the collection. Example in Javascript:
Meteor.subscribe('items', function () {
console.log(Items.find().count());
});

Should Backbone.js grab GET parameters from URL?

I am trying to implement a search function for my website. When the user types a search term foobar into a input box and submits it, he is redirected to http://mydomain.com/search?query=foobar.
Problem:: How should I grab the GET parameters query from the URL, and send it to the backend and get a array of results back as a JSON response? Should I even do it this way?
My current attempt below does not even cause the search function to be triggered.
Router
var AppRouter = Backbone.Router.extend({
routes: {
'search?query=:query': 'search'
// ... and some other routes
},
search: function(query) {
this.photoList = new SearchCollection();
var self = this;
this.photoList.fetch({
data: {query: query},
success: function() {
self.photoListView = new PhotoListView({ collection: self.photoList });
self.photoListView.render();
}
});
}
});
var app = new AppRouter();
Backbone.history.start({
pushState: true,
root: '/'
});
There have been several issues filed against Backbone for this very issue. There is an existing plugin that works well for this:
https://github.com/jhudson8/backbone-query-parameters
Alternatively, I'm currently using query string parameters in a mock API that matches Backbone's route matching. Looks something like this
Route
"/api/v2/application/:query"
Query
application: function(query) {
var params = $.deparam(query.slice(1));
// params.something...
}
As to your actual issue at hand how are you redirecting to index.html to support pushState?
I hit this same issue and contemplated using backbone-query-parameters, but that should be considered generally an incorrect approach.
The url query string is not meant for the front end. They get sent to the server and force a refresh when navigating from page.html to page.html?something=something.
You should be using hash fragments instead. i.e. http://www.example.com/ajax.html#key1=value1&key2=value2 then just get those values the normal backbone way and build your request params from that.
See https://github.com/jashkenas/backbone/issues/891, https://developers.google.com/webmasters/ajax-crawling/docs/specification, https://www.rfc-editor.org/rfc/rfc3986#section-3.5
You can always read the URL via jQuery URL plugin. It works well.
https://github.com/allmarkedup/jQuery-URL-Parser
There are very few cases when you need to read the URL and extract the GET params. I think that you are doing things wrong and here are my options:
1) if you are having just one page in your app (single app page) you can display results as they type in your input field or after they hit submit
2) if you are redirecting the user to a different page that means you can bootstrap data so that after the page is loaded backbone will just have to render your results and only make other requests if you change your search word
3) you can have a javascript variable which is initialized on page load directly from the server where working with GET params is probably easier

Categories