AngularJS how to make a POST JSON - javascript

I'm trying to make a post but below does not appear to work it does not post but console.log() looks like a put request i.e
http://127.0.0.1/api/v1/participant?account=%7B%22pk%22:1%7D&email=someemail#gmail.com
factory
app.factory('CbgenRestangular', function(Restangular) {
return Restangular.withConfig(function(RestangularConfigurer) {
RestangularConfigurer.setBaseUrl('http://127.0.0.1');
});
});
controller
$scope.participant = {email :$scope.email, password: "", account:{pk:1}};
CbgenRestangular.all('api/v1/participant').post("participant", $scope.participant);
What I'm I doing wrong?

according to the documentation (https://github.com/mgonto/restangular#lets-code):
// First way of creating a Restangular object. Just saying the base URL
var baseAccounts = Restangular.all('accounts');
var newAccount = {name: "Gonto's account"};
// POST /accounts
baseAccounts.post(newAccount);
note that post has a single input
you can add 'api/v1' to your base address - there's no need to carry it around (https://github.com/mgonto/restangular#setbaseurl)
I would also suggest using the plural form for a resource route, but that's a convention that some people don't follow - I guess it is a matter of taste

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

How to pass wildcard in vue js post request?

How I can get the current wildcard id and pass it to my $http.post route in vue?
Once I created a quiz information it will return a page with a new url
http://localhost:8000/question/index/quiz/3
Then when I want to do a post route with a name
Route::post('question/store/quiz/{quiz}');
Here is my Vue http request post method
this.$http.post('/question/store/'+ , input).then((response) => {
What will be id that I can pass after the + sign?
Well this is pretty hacky, but it'll work if your URLs are always going to be formatted like that. so what I'm doing here is using vanilla JS to get the URL pathname, parse the string by the / and turn it into an array, then grab the last index.
var locationString = location.pathname
var locationArray = locationString.split('/')
var quizId = locationArray[locationArray.length - 1];
The quizId variable is the wildcard you're looking for
You should note that this is going to break if you ever have any query parameters, such as a URL looking like: /index/quiz/3?v=2842

Angular CRUD parsing ID on resource remove

I'm trying to write a function to remove an answer:
// Remove an answer
$scope.removeAnswer = function(answer) {
Answers.remove(answer._id);
};
However, I am throwing the console error:
DELETE http://localhost:9000/api/answers?0=5&1=4&10=7&11=4&12=2&13=c&14=0&15=0&16=0&17=0&18=0&19=0&2=7&20=0&21=0&22=0&23=4&3=3&4=d&5=0&6=1&7=4&8=2&9=d 404 (Not Found)
When I console.log(answer._id), I get a reasonable id like 348374831...
Why is it converting the id to a weird format and how can I fix it?
Here seems to be an identical question, although the answer doesn't really explain the problem: AngularJS resource - encoding url string parameter as an array
The corect way to do it is:
$scope.removeAnswer = function(answer) {
Answers.remove({
id: answer._id
});
};
or instead of id use the corect name you used in the $resource factory definition.
Example:
var User = $resource('/user/:userId', {userId:'#id'});
User.get({userId:123}, function(user) {
user.abc = true;
user.$save();
});
$resource expects object parameter. Here's an example in Angular docs

How effectively updatie complex large object in REST?

Suppose I have a complex object from html page which is mapped to this JSON structure:
{
id:"", //is not shown to user
title : "",
description: "",
summary: "",
// other too many fields
}
To update this record with "common" REST approach I should use:
- POST rest/record/{id}
With "common" approach entirely record object is marshalled to JSON object and is passed to REST service, then this entirely object is validated, passed to SQL query to data base and DB engine updates a record with all data. But what if user just update one symbol in the title?
In that case I should split this object into several:
{
id:"", //is not shown to user
{ recordId:"", title : "", } ,
{ recordId:"", description: "", } ,
{ recordId:"", summary: "", } ,
// other too many fields
}
How I should reorganize rest URLs? Like that:
- POST rest/record/{id}/title
- POST rest/record/{id}/description
- POST rest/record/{id}/summary
- others
Is this approach with URL good or bad (I mean both for javaScript from end and REST back end programming)? Is there any other approaches to handle this problem?
Instead of using POST, use PATCH and send only what's been changed:
PATCH rest/record/{id}
Data: { title: "new title" }
URLs such as rest/record/{id}/title, rest/record/{id}/summary, etc. aren't really RESTfull since they are not resources but properties of a resource.
See this past question for some exploration of options here (include PATCH).
Best practice for partial updates in a RESTful service
You have the following options:
use PATCH and send only the title
use PUT and send the whole data again
use PUT and use the property as a sub-resource with url: /resource/title
(POST is not idempotent, so you should not use that for update)

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