AngularJS - $http.post send data as json - json

I'm working on autocomplete directive with angularjs but having some issues.
I have a form which have an autocomplete input. When i type something there, the term variable is sent as JSON:
But, when i use the same function (from different angular controller, but the same function) in another form the term variable sent perfectly and the autocomplete works fine:
Here is my angular function:
$scope.getCustomers = function (searchString) {
return $http.post("/customer/data/autocomplete",
{term: searchString})
.then(function (response) {
return response;
});
};
What do you think is wrong?

Use JSON.stringify() to wrap your json
var parameter = JSON.stringify({type:"user", username:user_email, password:user_password});
$http.post(url, parameter).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
console.log(data);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});

Consider explicitly setting the header in the $http.post (I put application/json, as I am not sure which of the two versions in your example is the working one, but you can use application/x-www-form-urlencoded if it's the other one):
$http.post("/customer/data/autocomplete", {term: searchString}, {headers: {'Content-Type': 'application/json'} })
.then(function (response) {
return response;
});

i think the most proper way is to use the same piece of code angular use when doing a "get" request using you $httpParamSerializer will have to inject it to your controller so you can simply do the following without having to use Jquery at all , $http.post(url,$httpParamSerializer({param:val}))
app.controller('ctrl',function($scope,$http,$httpParamSerializer){
$http.post(url,$httpParamSerializer({param:val,secondParam:secondVal}));
}

Related

loading multiple JSON files in AngularJS

I have two different JSON files and they have the same attributes in them. I'm able to load them by using two promises in my service but when I go in my HTML and try to display my data they display the same thing.
This is my service:
$http.get("data.json");
//User JSON api
$http.get("data1.json")
.then(function (response) {
dataRecievedCallback(response.data);
}
Should I assign my $http.get to a variable, if yes How can I do that and do I need to change anything in my controller?
I haven't been coding for long and I'm new to angular so all the help is appreciated.
$http.get("data.json")
.then(function (response) {
$scope.foo = response.data;
}
$http.get("data1.json")
.then(function (response) {
$scope.bar = response.data;
}
Not sure about your "dataRecievedCallback()" function, if your function set the data into the same variable, the second $http call will overwrite the first one.

HTTP Request returning empty element

I try to get a JSON object from a webservice with
MashupPlatform.http.makeRequest(url, {
method: 'GET',
requestHeaders: {"Accept": "application/json"},
forceProxy: true,
onSuccess: function (response) {
console.log("response: " + JSON.stringify(response));
success(response);
},
onFailure: function (response) {
error(response);
},
onComplete: function () {
complete();
}
});
but in the console every time an empty element ({}) gets logged. If I use curl to request that exact same URL I get the response I need. Is the wirecloud proxy unable to request application/json? In my browsers network analysis I see the request including the correct response, but the success function seems to not get that data.
WireCloud proxy supports application/json without any problem. Although the problem may be caused by other parameters, I think that your problem is related to a bad access to the response data. You should use response.responseText instead of using directly the response object (see this link for more info).

Consuming JSON string array, returned by a webservice, in AngularJS

There is a Webservice that is returning a json object in below format:
["Brazil","Argentina","Chile"]
(this json object has been parsed by Online JSON parsers, which proves it is a proper json object)
In AngularJS, I wrote the below code to consume the WebService.
app.factory('webServiceFactory', ['$http', function ($http) {
return $http.get('http://SomeWebService/api/anOperation')
.success(function (data) {
return data;
})
.error(function (err) {
return err;
});
}]);
When I call this in my controller, the success part is never hit and, instead, the error part is executed. That means there is some error calling the web-service. I think it has to do something with the JSON object that is being returned.
Edit 1: The Controller code
app.controller('mainController', ['$scope', 'webServiceFactory', function ($scope, webServiceFactory) {
webServiceFactory.success(function (data) {
$scope.Countries = data;
});
}]);
Edit 2: Localhost & CORS
When I hosted the service in my local IIS and consumed it using localhost, it worked. That means there is no error in consuming the JSON String array.
However, when I use a Fully qualified name or machine name, the FireFox indicates CORS header missing 'Access-Control-Allow-Origin'.
This might lead to another question, as to how to make it CORS compatible. However, the main question is closed.
So, my question, is How do I consume a web-service in AngularJS that returns just an array of strings with no Key/Value pair?
Thanks
maybe you are doing a request to a service in other domain; that is not possible since exists the "same origin policy" https://www.w3.org/Security/wiki/Same_Origin_Policy
app.factory('webServiceFactory', ['$http', function ($http) {
return
{
getCountries: function(callback){
$http.get('http://SomeWebService/api/anOperation').then(function(reponse){
callback(response.data);
});
}
};
}]);
Then in your controller
webServiceFactory.getCountries(function(countries){
$scope.countries = countries;
});

Node Express 4 get header in middleware missing

I have a middleware function using Node's Express4 to log each request & response for debugging. I use the res.json call in the request handler to send back JSON to the client for all but static files. So I do not want to log the response for static files, but only the JSON responses. I have the following code:
function logRequests(req, res, next) {
// do logging (will show user name before authentication)
logger.reqLog('IN '+req.method+' '+req.url, req);
var oldEnd = res.end,
oldWrite = res.write,
chunks = [];
res.write = function(chunk) {
chunks.push(chunk);
oldWrite.apply(res, arguments);
};
res.end = function(chunk, encoding) {
if(chunk) {
chunks.push(chunk);
}
oldEnd.apply(res, arguments);
// the content-type prints "undefined" in some cases
// even though the browser shows it returned as "application/json"
console.log('type='+res.get('content-type'));
if(res.get('content-type') === 'application/json') {
var body = Buffer.concat(chunks).toString('utf8');
logger.info(body, req);
}
logger.reqLog('OUT '+req.method+' '+req.path, req);
};
next(); // make sure we go to the next routes and don't stop here
}
So why do some requests show the correct content type in the middleware meaning they also print the response fine and others do not? All of them look good in the REST client when inspecting the returned headers.
EDIT: Some more info discovered tonight while trying to figure this out - if I append any character as a dummy request parameter, it logs the response type correctly:
http://localhost:8081/node/ionmed/api/logout?0 WORKS
where
http://localhost:8081/node/ionmed/api/logout DOES NOT
Also, I can always get a response type logging in the middleware function if I replace the .json() call with .end() so this:
res.json({ item: 'logout', success: true });
becomes:
res.set('content-type', 'application/json');
res.end({ item: 'logout', success: true });

AngularJS ngResource Send data to server with JSON and get response

In my angular JS app i need to send data to server:
"profile":"OLTP",
"security":"rsh",
"availability":"4",
"performance": {
"TRANSACTION_PER_SEC":1000,
"RESPONSE_TIME":200,
"CONCURRENT_CONNECTION_COUNT":500,
"STORAGE_SIZE":200,
"TOTAL_CONNECTION_COUNT":500
}
and in return i'll get
{"estimate" : 1600,"quoteid" : "Q1234"}
I was trying to do that with $resource but I am lost in syntax.
app.factory("VaaniEstimateService", function($resource) {
var requestURL = "http://128.34.32.34:8080/enquiry";
return $resource(requestURL, {callback: 'JSON_CALLBACK'}, { get: { method:'JSON'}, isArray:false });
});
Can you please provide me something to get me on the right path.
You must use JSONP method and insert JSON_CALLBACK keyword to your url as callback function.
app.factory("VaaniEstimateService", function($resource) {
return $resource("http://128.34.32.34:8080/enquiry?callback=JSON_CALLBACK", {}, {
get: {
method:'JSONP'
},
isArray:false
}).get({
profile:"OLTP",
security:"rsh",
availability:"4",
"performance.TRANSACTION_PER_SEC":1000,
"performance.RESPONSE_TIME":200,
"performance.CONCURRENT_CONNECTION_COUNT":500,
"performance.STORAGE_SIZE":200,
"performance.TOTAL_CONNECTION_COUNT":500
}, function (response) {
console.log('Success, data received!', response);
});
});
Your params will be sent as query params. Angularjs will automatically generate a global function for callback and replace its name with JSON_CALLBACK keyword. Your server must return json as javascript code by calling function that sent with callback parameter. For example, AngularJS is going to make GET request to that url:
http://128.34.32.34:8080/enquiry?callback=angular.callbacks._0?availability=4&performance.CONCURRENT_CONNECTION_COUNT=500&performance.RESPONSE_TIME=200&performance.STORAGE_SIZE=200&performance.TOTAL_CONNECTION_COUNT=500&performance.TRANSACTION_PER_SEC=1000&profile=OLTP&security=rsh
And your server must return response like that:
angular.callbacks._0({"estimate" : 1600,"quoteid" : "Q1234"});
Hope that's enough to give you an idea how jsonp works.