Why does my $http put not actually send any data? - angularjs

I am using the following code block:
app.putConfigs = function () {
$http({
data: app.config,
headers: app.user.getHeaders(),
url: '/api/Config/Put',
method: "PUT"
});
}
As far as I can see this is the same as in the angular documentation. app.config is an object.
When I check with fiddler no JSON data is being sent to the server.
Is there something wrong with the way I am using $http ?

I would start with something simple to help diagnose your problem. See if this works:
$http.put('/api/config', { key: 'test' }).then(function(resp) {
console.log(resp);
});
Docs ref: https://docs.angularjs.org/api/ng/service/$http#put

Related

Angular: $http change method on adding data with post

I am using fuse template and accessing my web service by using $http, its working fine if i am using method: 'POST' without send any data but whenever i am adding some data with post like: data: {text:'test'} and send request to my web service its change the method type POST to OPTIONS.
My Code:
$scope.submit = function(){
$http({
method: 'POST',
url: 'http://www.example.com/api-link',
data: {test: 'hello'},
header: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function(result){
console.log(result);
});
}
When i am checking in browser network its showing method type OPTIONS. Can anyone please tell what is wrong in my code?
Thanks

Angular $resource POSTing entire object, not just properties passed to it

I'm using Angular's $resource to interface with an API, and creating custom methods on that resource. One of these methods is a POST, and when I attempt to use it, it's sending the entire resource, not just the properties I'm attempting to post to the API. I don't think this is the intended behavior of the $resource service, but then, I might be missing something.
Here's the code:
The service:
angular.module('adminApp')
.factory('Framework', function($resource) {
return $resource('/api/frameworks/:id', {id: '#id'}, {
'update': {
method: 'PUT'
},
'getRequiredLicenses': {
method: 'GET',
url: '/api/frameworks/:id/required_licenses',
isArray: true
},
'addRequiredLicenses': {
method: 'POST',
url: '/api/frameworks/:id/required_licenses'
},
'removeRequiredLicense': {
method: 'DELETE',
url: '/api/frameworks/:id/required_licenses/:license_id'
}
});
});
Where I'm calling it:
scope.addLicensesToFramework = function() {
scope.framework.$addRequiredLicenses(null, {
required_licenses: Object.keys(scope.selectedLicenses) // returns an array of ints
});
}
(Note that this is in a directive. scope.framework is the instance of the framework resource)
When this request is sent, here's what's being included in the payload:
My intention is to only pass {'required_licenses': [12345,1236]} in the payload, and I can't seem to figure out why it's sending the entire resource as the body. (It's, in fact, not sending this at all, only the original resource)
Any insight would be really helpful, thanks!
Try calling it like this:
scope.addLicensesToFramework = function() {
scope.framework.$addRequiredLicenses({
required_licenses: Object.keys(scope.selectedLicenses),
id: 1234
}, function(resp){ console.log(resp) });
}
Also notice that I included the id in the parameters object.. you'll probably need that.

Slim, Postman and AngularJs : $app->request->getBody() vs $app->request->post()

I'm a beginner. I've written a test application made of an AngularJs GUI on the client side and a PHP API on the server side.
This is the angular service handling the requests
myApp.factory('Book', ['$resource', 'API_URL', function($resource, API_URL){
return $resource(API_URL + '/books/:bookId', {bookId: '#bookId'}, {
get: { method: 'GET', isArray:true },
update: { method: 'PUT'},
save: { method: 'POST'},
delete: {method:'DELETE'},
});
}]);
When I submit a book from the Angular app I can catch the POST in Slim by using
$post_a = json_decode($app->request->getBody());
//$post_b = $app->request->post(); //this would be empty
When I use Postman and I perform a POST I can catch the POST in Slim by using
//$post_a = json_decode($app->request->getBody()); // this would be empty
$post_b = $app->request->post();
I don't get why there is this difference. Could you please explain?
Am I not meant to catch the post just with $app->request->post(); in both the cases? Why the post coming from Angular can be caught only with $app->request->getBody()?
The $app->request->post() method retrieves key/value data submitted in a application/x-www-form-urlencoded request. If the request uses a different content-type (e.g. application/json), you can retrieve the raw request body with the $app->request->getBody() method and decode it as necessary. Let me know if you have further questions.
You could still use
$post_b = $app->request->post()
in Slim.
As long as you call this REST service from html form (AngularJS) by passing the data as form value formatted instead of as JSON.
If in AngularJS you have the data in JSON format, you have to translate it first into form. Below is the example how to invoke this REST service:
Object.toparams = function ObjecttoParams(obj) {
var p = [];
for (var key in obj) {
p.push(key + '=' + encodeURIComponent(obj[key]));
}
return p.join('&');
};
$http({
method: 'POST',
url: url,
data: Object.toparams(myobject),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
myobject is the data in JSON format that is going to be created
Thanks Josh..Your answers works for me.
Steps to follow:
1.You need to send request in json format under raw tab like this:
{"username":"admin","password":"admin"}
2.You need to set Content-Type to application/json in the headers.
That's it and it will work.

how to get results of my webservice with jsonp?

I want to call one of my webservices via jsonp with angularjs.
When i call http://example.com/files?callback=JSON_CALLBACK directly in my browser, i got :
["folder1", "folder2"]
When i call from angularjs with :
$http.jsonp('http://example.com/files?callback=JSON_CALLBACK')
.success(function(data){
console.log(data);
$scope.folders = data;
});
console.log does not appear....
What am i doing wrong ?
Must my webservice return
JSON_CALLBACK(["folder1", "folder2"])
? Should i do it manually in my api ? browser don't do that automatically ?
What you are currently returning (["folder1", "folder2"]) is not valid JSONP. The JSON result must be wrapped by a javascript function call in order to be valid JSONP.
For example, when you use the URL like this:
http://example.com/files?callback=JSON_CALLBACK
Angular will replace the JSON_CALLBACK parameter with an angular function name (created internally), like:
http://example.com/files?callback=angular.callbacks._0
Your server would then need to be able to read that callback parameter and return the result like this:
angular.callbacks._0(["folder1", "folder2"]);
This is not an automatic mechanism, you need to implement that logic on your web server.
Try Using Following code snippet.
(function($) {
var url = 'http://example.com/files?callback=JSON_CALLBACK';
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(data) {
console.dir(data);
},
error: function(e) {
console.log(e.message);
}
});
})(jQuery);
bmleite was right, I had to implement this logic on my API.
In my example, my server is made with Silex :
public function index()
{
$callback = $this->request->get('callback');
$files = $this->app['file.manager']->getList();
$response = new \Symfony\Component\HttpFoundation\JsonResponse();
$response->setData($files);
$response->setCallback($callback);
return $response;
}
And it works perfectly now. Thank you.

How to Format Rexster POST to Add an Edge to a Titan Graph

I'm attempting add an edge to my Titan Server 0.4.4 graph using an AngularJS resource. The resource looks like this:
'use strict';
angular.module('storymapApp').factory('edgeResource', function ($resource) {
var EdgeResource = $resource('http://localhost:8182/graphs/graph/edges?_outV=:outId&label=:label&_inV=:inId', {outId: "#outId", inId: "#inId", label: "#label"}, {
update: {method: 'PUT', isArray: false},
outedge: {method: 'POST',
transformResponse: function(data, headers){
// deserialize the JSON response string
data = angular.fromJson(data);
data = data.results;
return data;
},
isArray: true}
});
return EdgeResource;
});
This code generates a POST like this:
http://localhost:8182/graphs/graph/edges?_outV=120028&label=contains&_inV=160076
which returns the following 500 error message:
{"message":"An error occurred while generating the response object","error":"Edge cannot be found or created. Please check the format of the request."}
Where is the formatting issue in the request?
Can you change your angularjs code to POST the request as JSON (instead of formatting the parameters to query string)? Set your Content-Type to application/json as well (though angular may be doing that for you already. Those things should fix your problem.

Resources