Incorrect syntax.. probably missing one minor detail - angularjs

Sending an http request form angular to spring and I'm getting the syntax is incorrect response. Whats weird is I'm not doing anything special and this same formula is working in 100 other places.. any help is much appreciated
"NetworkError: 400 Bad Request - http://localhost:8080/accounts/1/groups/GroupedDisplay"
The request sent by the client was syntactically incorrect.
Java
#RequestMapping(value = "/accounts/{accountId}/groups/{groupName}", method = RequestMethod.POST)
public JSONObject createGroup(#RequestBody Display display, #PathVariable("accountId") Long accountId, #PathVariable("groupName") String groupName) {
return JsonResponse.generateResponse("display", groupService.createGroup(accountId, groupName, display), null);
}
Angular
function getUrl(suffix) {
if (suffix)
return 'http://localhost:8080/accounts/'+getAccountId()+'/groups/'+suffix;
else
return 'http://localhost:8080/accounts/'+getAccountId()+'/groups';
}
...
createGroup: function(groupName, display) {
var deferred = $q.defer();
$http.post(getUrl(groupName), display)
.success(function (response) {
var display = response.data.display;
deferred.resolve(new Display(display));
})
.error(function(response) {
deferred.reject('Failed to retrieve display: ' + response.message);
});
return deferred.promise;
},

Related

Angularjs $http get not working

I am trying to access REST web service from angularjs. I am not able to call it successfully.
AngularJs Code
var singleOrderUrl = "/singleOrder/retrieve";
function getSingleOrderDetails(userName,singleOrderUrl,$http,$q) {
var fd = new FormData();
var deffered = $q.defer();
fd.append('USERNAME', 'test123');
//fd.append();
//fd.append();
console.log("inside service"+userName+"singleOrderUrl:::"+singleOrderUrl);
return $http.get(singleOrderUrl, fd, {
withCredentials : false,
transformRequest : angular.identity,
headers : {
'Content-Type' : undefined,
}
}).success(function(response) {
console.log(response);
responseData = response.data.toString();;
deffered.resolve(response);
return responseData;
}).error(function(error) {
alert("error");
deffered.reject(error);
return "failed";
});
};
Rest Service code
#RestController
public class SingleOrderHistoryController {
private static final Logger logger = LoggerFactory.getLogger(SingleOrderHistoryController.class.getName());
#RequestMapping(value = "/singleOrder/retrieve", method=RequestMethod.GET, produces="application/json")
public List<SingleHistoryRecord> getSingleOrderDetails(#RequestParam(value = Constants.USER_NAME, required = true) String userName, HttpServletRequest request,HttpServletResponse response) throws Exception {
logger.debug("inside SingleOrderHistoryController ");
List<SingleHistoryRecord> singleOrderHistoryList = new ArrayList<SingleHistoryRecord>();
SingleHistoryRecord record1 = new SingleHistoryRecord();
SingleHistoryRecord record2 = new SingleHistoryRecord();
record1.setClientIdentifier(userName);
record1.setSubmitDate("01/05/2017");
record1.setStatus("Complete");
record1.setReferenceID("1234555");
record1.setOrderID("test123");
record2.setClientIdentifier(userName);
record2.setSubmitDate("01/05/2017");
record2.setStatus("Complete");
record2.setReferenceID("1234555");
record2.setOrderID("test123");
singleOrderHistoryList.add(record1);
singleOrderHistoryList.add(record2);
return singleOrderHistoryList;
}
Can anyone please advise what I am doing wrong here, It is getting the source code of the page in response instead of getting the list.

How to return data from Web Api controller?

Hi I am developing restfull web api application. After inserting data into database i want to return 0 for success,1 for error and data as unique id assigned to the user. I want to return above data in json format. My requirement is i have to send data to controller in json format and receive data in json format. I have following code and it is working but i want to ask few points here.
Below is my User_Creation controller code.
public result Post(Noor_Users users)
{
result obj = new result();
if (ModelState.IsValid)
{
entityObject.Noor_Users.Add(users);
int result = entityObject.SaveChanges();
if(result==1)
{
obj.success = 0;
obj.id = 5;
return obj;
}
else
{
obj.error = 1;
return obj;
}
}
else
{
obj.error = 1;
return obj;
}
}
}
My service.js file contains below code.
app.service("UserCreation", function ($http) {
this.saveSubscriber = function (sub) {
return $http({
method: 'post',
data: JSON.stringify(sub),
url: 'api/User_Creation',
contentType: "application/json"
});
}
});
This is my controller.js code.
app.controller('UserCreation', function ($scope, UserCreation) {
$scope.saveSubs = function () {
var sub = {
user_email: $scope.user_email,
user_password: $scope.user_password,
};
var saveSubs = UserCreation.saveSubscriber(sub);
saveSubs.then(function (data) {
alert(JSON.stringify(data.data));
}, function (error) {
console.log('Oops! Something went wrong while saving the data.')
})
};
});
I am expecting response in json format as below.
● status - 0 for success, 1 for failure.
● data
○ id - unique id assigned to the user
● error - error message if failed
This is working absolutelt fine. I have below line of code in webapiconfig.cs file
config.Formatters.JsonFormatter.SupportedMediaTypes
.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("text/html"));
With this line of code always i can receive data in json format. But in angularjs success call i need to stringify recieved data. If all my data is returning in json then again why i should convert it to json? Also someone can tell me is above logic is a good practice to return data? Thank you.
Try the following steps:
Add this two line of code on top of your WebApiConfig.cs
public static void Register(HttpConfiguration config)
{
config.Formatters.Clear();
config.Formatters.Add(new JsonMediaTypeFormatter());
Edit you controller action with following one
public IHttpActionResult Post(Noor_Users users)
{
result obj = new result();
if (ModelState.IsValid)
{
entityObject.Noor_Users.Add(users);
int result = entityObject.SaveChanges();
if (result == 1)
{
obj.success = 0;
obj.id = 5;
}
else
{
obj.error = 1;
}
}
else
{
obj.error = 1;
}
return Ok(obj);
}

Getting status 500 when using angularjs $http to get data from server

I am working on an asp.net mvc application and I am using Entity Framework and AngularJS in it. I am using AngularJS's $http service to call an action method and retrieve data from the server. The correct data is retrieved from the server (I confirmed this by debugging), but somehow an error occurs after the action method returns the retrieved data and the error callback function is fired instead of the success callback function. And then I get a status 500 in the browser's console.
Here are the involved blocks of codes:
(From angularjs controller)
$http({
url: rootUrl + "User/GetUser",//'#Url.Action("GetUser","User")',
method: 'POST',
params: {
uname: $scope.username,
pword: $scope.pass
}
}).then(function (response) {
alert('success!');
$scope.user = response.data;
if ($scope.user.Fullname != undefined) {
$http({
url: rootUrl + "Session/Set",
method: "POST",
data: {
"key": "curr_user",
"value": JSON.stringify($scope.user)
}
});
window.location.href = rootUrl + 'Product/List/';
} else {
//invalid login
$("input[name='password']").select();
$("#validation-summary").html("Wrong email or password.");
$scope.invalidlogin = true;
$(btnLogin).removeClass('disabled');
$(btnLogin).text("Submit");
}
(From mvc controller)
[HttpPost]
public JsonResult GetUser(string uname, string pword)
{
JBManager manager = null;
using (SE_Context db = new SE_Context())
{
try
{
manager = db.Managers
.Include("Transactions.Items")
.Where(m => m.Username == uname && m.Password == pword)
.FirstOrDefault();
//At this point, manager has the desired data
return Json(manager, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return null;
}
}
}
And here's a screenshot of the error in the browser:
Would really appreciate any help. Thanks!
UPDATE:
Everything was working fine before I used Entity Framework. (Just in case it has something to do with the issue)
I think your issue is nested objects.You can flatten object graphs that contain nested objects using DTOs (Data Transfer Objects).
You can just try simple example as like below.If it'll work then you need to extend it to work with your EF query.
public class MyDto
{
public string Name { get; set; }
}
[HttpPost]
public JsonResult GetUser(string uname, string pword)
{
JBManager manager = null;
using (SE_Context db = new SE_Context())
{
try
{
//construct the DTO here
manager = db.Managers.Select(a=> new MyDto(
{
Name = a.Name
})).FirstOrDefault(m => m.Username == uname && m.Password == pword);
return Json(manager, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return null;
}
}
}
You can read more about DTOs here : Create Data Transfer Objects (DTOs)

Spring Data Jpa, REST, org.springframework.beans .TypeMismatchException from Angularjs front end

I have request from my Angularjs factory is as follows:
.factory('TrackingNumberDetailsUpsGeneralService', function ($http) {
return {
findByInvoiceDetailsId: function (invoiceDetails) {
console.log("invoiceDetails " + invoiceDetails.id);
return $http.get('/api/trackingNumberDetailsUpss/byInvoiceDetailsId', {params: {invoiceDetailsId : invoiceDetails.id}}).then(function (response) {
return response.data;
});
}
};
});
And in my Tracking...Resource.java, I have
#RequestMapping(value = "/trackingNumberDetailsUpss/byInvoiceDetailsId/",
method = RequestMethod.GET,
produces = MediaType.APPLICATION_JSON_VALUE)
#Timed
public List<TrackingNumberDetailsUps> findByInvoiceDetailsId(#RequestParam(value="invoiceDetailsId") Long invoiceDetailsId,
#RequestParam(value = "page" , required = false) Integer offset,
#RequestParam(value = "per_page", required = false) Integer limit) {
log.debug("REST request to get TrackingNumberDetailsUps By Invoice Details Id " + invoiceDetailsId);
return trackingNumberDetailsUpsService.findByInvoiceDetailsId(invoiceDetailsId);
}
But I am getting the following error:
http://localhost:8080/api/trackingNumberDetailsUpss/byInvoiceDetailsId?cacheBuster=1444014377012&invoiceDetailsId=2 400 Bad Request
{"timestamp":1444015194707,"status":400,"error":"Bad Request","exception":"org.springframework.beans
.TypeMismatchException","message":"Failed to convert value of type 'java.lang.String' to required type
'java.lang.Long'; nested exception is java.lang.NumberFormatException: For input string: \"byInvoiceDetailsId
\"","path":"/api/trackingNumberDetailsUpss/byInvoiceDetailsId"}
I am not able to figure out where is the problem. Can any one help me in resolving this.
The following is my Request :
.factory('TrackingNumberDetailsUpsGeneralService', function ($http) {
return {
findByInvoiceDetailsId: function (invoiceDetails) {
console.log("invoiceDetails " + invoiceDetails.id);
return $http.get('/api/trackingNumberDetailsUpss/byInvoiceDetailsId', {params: {invoiceDetailsId : invoiceDetails.id}}).then(function (response) {
return response.data;
});
}
};
});
Try removing the extra / from the end of your #RequestMapping annotation.
It does matter - just tested.

Unexpected token , in Angular code after $http request

I am submitting an $http request to my server using this code below, yet all the of sudden Angular is complaining about an "Unexpected token , " somewhere.
function sendAggrRequestToServer(url) {
var deferred = $q.defer();
$http({
method: 'GET',
encoding: 'JSON',
headers: {
'Access-Control-Allow-Origin': 'true'
},
withCredentials: true,
url: url
}).success(function (data, status, headers, config) {
var retval = data;
deferred.resolve(retval);
}).error(function (data, status, headers, config) {
logErr("Error submitting aggregation request to server: " + status);
});
return deferred.promise;
}
The strange thing is that this exact URL works successfully both in the browser and in Fiddler. And the Json data is returned as expected. However, for some strange reason my javascript code is throwing this
exception:
[app] [HT Error] Unexpected token ,
Object {exception: SyntaxError, cause: undefined}
angular.js:9778
(anonymous function) angular.js:9778
logIt logger.js:55
logError logger.js:49
(anonymous function) logger.js:32
(anonymous function) config.exceptionHandler.js:26
deferred.promise.then.wrappedCallback angular.js:11322
(anonymous function) angular.js:11405
Scope.$eval angular.js:12412
Scope.$digest angular.js:12224
Scope.$apply angular.js:12516
done angular.js:8204
completeRequest angular.js:8412
xhr.onreadystatechange
And my URL is :
http://localhost:49479/api/aggr?sid=9630a8040ee6c901a4034c07894abc317272f855c757a4c60a6a&kri=[CDSStress%20A]:[USD%2010Y%20X%20-1.25],[CDSStress%20A]:[USD%2010Y%20X%201.25]&aggrFunc=SUM([CDSStress%20A]:[USD%2010Y%20X%20-1.25]),SUM([CDSStress%20A]:[USD%2010Y%20X%201.25])&dim=Counterparty
FYI: All appears to be fine in angular.js at this point in angular, and I can indeed see the response data (which is definitely valid Json data). The callback status param has a value of "200" and the statusText is 'OK':
function completeRequest(callback, status, response, headersString, statusText) {
// cancel timeout and subsequent timeout promise resolution
timeoutId && $browserDefer.cancel(timeoutId);
jsonpDone = xhr = null;
// fix status code when it is 0 (0 status is undocumented).
// Occurs when accessing file resources or on Android 4.1 stock browser
// while retrieving files from application cache.
if (status === 0) {
status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0;
}
// normalize IE bug (http://bugs.jquery.com/ticket/1450)
status = status === 1223 ? 204 : status;
statusText = statusText || '';
callback(status, response, headersString, statusText);
$browser.$$completeOutstandingRequest(noop);
}
};
Here is a screen image of the break point where I can inspect the "response" param:
However, as soon as it resolves the promise and returns to my calling function, angular throws the Unexpected token error.
I have been using this for days now, but today I must have introduced something to cause this. I just can't figure out what !
Your advice and guidance is greatly appreciated.
regards.
Bob
UPDATE:
I now find Angular throwing the actual exception inside $HttpProvider() on this line :
data = fromJson(data);
inside here :
function $HttpProvider() {
var JSON_START = /^\s*(\[|\{[^\{])/,
JSON_END = /[\}\]]\s*$/,
PROTECTION_PREFIX = /^\)\]\}',?\n/,
CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': 'application/json;charset=utf-8'};
var defaults = this.defaults = {
// transform incoming response data
transformResponse: [function(data) {
if (isString(data)) {
// strip json vulnerability protection prefix
data = data.replace(PROTECTION_PREFIX, '');
if (JSON_START.test(data) && JSON_END.test(data))
data = fromJson(data);
}
return data;
}],
// transform outgoing request data
transformRequest: [function(d) {
return isObject(d) && !isFile(d) && !isBlob(d) ? toJson(d) : d;
}],
// default headers
headers: {
common: {
'Accept': 'application/json, text/plain, */*'
},
post: copy(CONTENT_TYPE_APPLICATION_JSON),
put: copy(CONTENT_TYPE_APPLICATION_JSON),
patch: copy(CONTENT_TYPE_APPLICATION_JSON)
},
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN'
};
And sendAggregationREquest() is called from here :
function buildAndSendAggregationQuery() {
// iterate list in reportsContext , pass data to to sendAggregationRequest()
var userKRIs = vm.kriUserDataSource.get();
userKRIs.load();
var group;
var kri = '';
var aggrFunc = '';
var aggrKriFuncArray;
var dimension = vm.selectedDimen;
var dimenMulti = '';
var applyScenarioAggr = false;
if (vm.kriUserDataSource.data()[0].group == '99_HSVaR') {
applyScenarioAggr = true;
}
// Call function to build the aggr function. Return value is an array.
if (applyScenarioAggr) {
aggrKriFuncArray = reportsContext.buildAggrFunc(vm.kriUserDataSource.data(), 'AVERAGE');
}
else {
aggrKriFuncArray = reportsContext.buildAggrFunc(vm.kriUserDataSource.data(), 'SUM');
}
kri = aggrKriFuncArray[0];
aggrFunc = aggrKriFuncArray[1];
for (var i = 0; i < vm.multiSelectedDimen.length; i++) {
dimenMulti += vm.multiSelectedDimen[i] + ',';
}
dimenMulti = dimenMulti.substr(0, dimenMulti.length - 1); // ' remove final ","
sendAggregationRequest(kri, aggrFunc, dimension); //dimenMulti);
}
and finally, the response data that comes back from server prior to that exception:
{"status":"SUCCESS", "messages":[], "data":[{"attributes":[{"name":"Counterparty","type":"string"},{"name":"SUM(CDSStress A:USD 10Y X -1.25)","type":"double"},{"name":"SUM(CDSStress A:USD 10Y X 1.25)","type":"double"}],"rows":[{"id":0,"values":["Goldman",0.,0.]},{"id":1,"values":["IBM",0.,0.]},{"id":2,"values":["JP Chase",0.,0.]},{"id":3,"values":["MINESCONDIDA",0.,0.]},{"id":4,"values":["Merrill",0.,0.]},{"id":5,"values":["Nokia",0.,0.]},{"id":6,"values":["Pequot",0.,0.]},{"id":7,"values":["Pimco Fund A",0.,0.]},{"id":8,"values":["Pimco Fund B",0.,0.]},{"id":9,"values":["Deutsche",0.,0.]},{"id":10,"values":["Ditech",0.,0.]},{"id":11,"values":["GM Isuzu",0.,0.]},{"id":12,"values":["GM Opel",0.,0.]},{"id":13,"values":["GMAC",0.,0.]},{"id":14,"values":["GMAC Insurance",0.,0.]},{"id":15,"values":["GSAM",0.,0.]},{"id":16,"values":["General Insurance",0.,0.]},{"id":17,"values":["Genworth",0.,0.]},{"id":18,"values":["AIG",0.,0.]},{"id":19,"values":["Andor",0.,0.]},{"id":20,"values":["BARCLAYS",92.7731197209214,-10.1717767200607]},{"id":21,"values":["BHHSH",0.,0.]},{"id":22,"values":["BHPBFIN",0.,0.]},{"id":23,"values":["BHPSTEEUR",1468.80370935,-161.395632863801]},{"id":24,"values":["BHPSUS",0.,0.]},{"id":25,"values":["BLUESCOPEFIN",0.,0.]},{"id":26,"values":["CSFB",3.35029024626419,-0.367366071961442]},{"id":27,"values":["BLOSOFL",0.,0.]},{"id":28,"values":["GRMOBND",0.,0.]}]}]}
can you make a jsfiddle ? or at least show us how you call the sendAggrRequestToServer method.
It shouldbe
var promise = sendAggrRequestToServer(url);
promise.then(function(data) {
console.log('Success we got: ' + data);
}, function(reason) {
console.log('Failed we got: ' + reason);
}, function(update) {
console.log('Strange we got: ' + update);
});
Thx

Resources