I'm trying to call a webservice that requires me to pass a JSON object to it. Though I'm not sure whether I'm doing it right. My service does the following:
this.updateAddressDetails = function (address, personId) {
var url = 'http://213.456.123.456:8080/Address?' +
'action=updateAddress' +
'&personId=' + personId +
'&address=' + JSON.stringify(address);
return $http.get(url);
}
But I get the following error server side (I'm using Java Servlets):
Error parsing HTTP request header
Which leads me to assume that I'm not passing the JSON to the server the correct way. Any tips?
Try something like this if your are working with angular JS:
$scope.myFunc = function() {
// Simple POST request example (passing data) :
$http.post("/createProject/"+ id +"", {
projectTitle: pTitle,
userID : id
}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
console.log("project created");
console.log("this is the response data " + data);
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
};
Related
I have Web Api calls that I make via angular $http , What I need to do are some various options.
Call Web Api endpoint which will then create an XML file on the file system of which I need to be able to have my Angular application display the XML in another window - would this be done a specific way with angular?
Like to Also be able to stream in memory the xml to be in angular as a string for me to decide how to parse thoughts?
I do see code like below, which is "nice" , but I don't want to just convert xml to json
angular.module('myApp',[]).factory('DataSource', ['$http',function($http){
return {
get: function(file,callback,transform){
$http.get( file, {transformResponse:transform} ).
success(function(data, status) {
console.log("Request succeeded", data);
callback(data);
}).error(function(data, status) {
console.log("Request failed " + status);
});
}
};
}]);
var AppController = function($scope,DataSource) {
var SOURCE_FILE = "timer.xml";
xmlTransform = function(data) {
console.log("transform data");
var x2js = new X2JS();
var json = x2js.xml_str2json(data);
return json.TimerStatus;
};
setData = function(data) {
console.log("setdata", data);
$scope.dataSet = data;
};
DataSource.get(SOURCE_FILE,setData,xmlTransform);
};
I am returning a java object to client(javascript) page, i.e. converting java object to JSON object but am facing no converter found for return value error.
I have added all spring jars and jackson-all-xxx.jar.
The below is the method that gets called from a html page using $http.get('url').
#RequestMapping(value="/springAngularJS",method=RequestMethod.GET)
public #ResponseBody Person getPerson() {
System.out.println("111111111");
Person person = new Person();
person.setFirstName("Java");
person.setLastName("Honk");
return person;
}
My html page: (posting only JS part)
var app = angular.module('myApp', []);
function MyController($scope, $http){
$scope.getPersonDataFromServer = function() {
$http.get("springAngularJS").
success(function(data, status, headers, config) {
$scope.person = data;
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
};
};
Any help to resolve this would be appreciated..
I am a beginner..:)
Your problem is with project dependency and not code , as the above code is correct .
Again I suggest on you to start with Spring-boot it will allow you to concentrate on the code only working example
Displayed below is my WebAPI method which returns a list of Information about several books.
[System.Web.Http.Authorize]
public async Task<IHttpActionResult> Get(Guid id)
{
try
{
var result = await _assetAssetRepository.View(id);
if (result == null)
{
return NotFound();
}
return Content(HttpStatusCode.Found, result);
}
catch (Exception ex)
{
return Content(HttpStatusCode.InternalServerError,
"Exception Occurred" + ex.Message + " " + ex.StackTrace);
}
}
Angular js code to consume this data
var getAssetDetails = function (assetId) {
var deferred = $q.defer();
$http.get("/api/Asset/" + assetId, { headers: { 'Authorization': 'Bearer ' + $cookies.get('accessToken') } })
.then(function (response) {
deferred.resolve(response);
}).catch(function (response) {
alert("Oops something wrong: " + response.data);
deferred.reject(response);
}).finally(function () {
});
return deferred.promise;
};
The bit i am struggling is if you replace this line of code in webapi
"return Content(HttpStatusCode.OK,result)" with "return Ok(result)" i can see the data in the UI without any problem. However when i use "return Content(HttpStatusCode.OK,result)", the angular code for some cannot read this and throws out exception and shows the alert message saying "Oops something wrong [object Object]" so it seems like its getting the data but for some reason its still throwing exception. Anyone up for help?
Well, it's best to start with details given by the catch block. But one of many errors can be (which I first had):
Unexpected token R in JSON at position 0
which is be due to responseType: 'JSON' added in your http request. Angular takes the response as JSON where in this case it is not. So we need to remove this.
Here is how I do it (end-to-end). From my API:
return Content(HttpStatusCode.<statuscode>, "ResponseContent: " + "my_custom_error");
Second Case:
//If I'm getting output from another API/Layer then I pass it's output like this
var output = response.Content.ReadAsStringAsync().Result;
return Content(response.StatusCode, "ResponseContent: " + output);
And in the Angular code, I read it like this:
$http({ method: methodType, url: endpoint })
.then(function (response) {
response.status; //gets you the HttpStatusCode to play with
response.data; //gets you the ReponseContent section
}, function (response) {
response.status; //gets you the HttpStatusCode
response.data; //gets you the ReponseContent section
});
From https://docs.angularjs.org/api/ng/service/$http
The response object has these properties:
data – {string|Object} – The response body transformed with the
transform functions.
status – {number} – HTTP status code of the response.
headers – {function([headerName])} – Header getter function.
config – {Object} – The configuration object that was used to
generate the request.
statusText – {string} – HTTP status text of the response.
First of all my apologies if the question is repeated.
I am making ajax requests using $q service.
UtilityService.requestCall('/test/encrypt-data', {'json_string' : data_to_encrypt, 'encryption_key' : window.localStorage.getItem("Mi_Encryption_Key")})
.then(function(encrypt_response) {
var requestConoce = parseInt(window.localStorage.getItem("Mi_Cnonce")) + 1;
window.localStorage.setItem("Mi_Cnonce", requestConoce);
requestData['cnonce'] = requestConoce;
requestData['encrypted_data'] = encrypt_response.data;
return UtilityService.requestCall($scope.apiDetails.url, requestData, 'GET');
})
.then(function(api_response) {
var requestConoce = parseInt(window.localStorage.getItem("Mi_Cnonce")) + 1;
window.localStorage.setItem("Mi_Cnonce", requestConoce);
return UtilityService.requestCall('/test/decrypt-data', {'encrypted_string' : api_response.encrypted_data, 'encryption_key' : window.localStorage.getItem('Mi_Encryption_Key') });
})
.then(function(decrypt_response) {
$scope.serverResponse = JSON.stringify(decrypt_response);
return;
})
.catch(function(error) {
alert("Some Error");
})
MyApp.factory('UtilityService', ['$http', '$q', function($http, $q) {
return {
requestCall: function(requestUrl, requestData, methodType) {
var deferred = $q.defer();
var serverUrl = window.localStorage.getItem("Mi_Server_Url");
$http({
method: (methodType) ? methodType : "POST",
url: serverUrl + requestUrl,
data: requestData
})
.then(function(result) {
deferred.resolve(result.data);
},
function(error) {
deferred.reject(error);
});
return deferred.promise;
}
};}]);
I am making requests using the above code. It is working fine for the request "/test/encrypt-data"
But then request for $scope.apiDetails.url is not working. Request is made without any parameters But, I am sending all required parameters in requestData.
This code working for other (even I am sending the data) but not working for this request.
It seems angularjs requests two time for the same request once without data and other with data.
Please help for this strange issue. Please take a look on these images these are showing two different requests once with data and other without data.
First of all you are getting two requests because one of them is the OPTIONS call and one is the actual POST call. This is the normal behaviour and nothing to worry about.
The second request you are making is a GET request which cannot contain any POST-Data. This is just not supported by HTTP.
So depending on what the backend is expecting you could either turn that request into a POST request or you could add the data as GET parameters which is described here: in the Angular docs
I have an Angular form connected to a REST API to insert a new row to a MySQL database. My REST API is working, but I am getting a CORS blocked notice in my web console. How can I get it to successfully send to the REST PI? Below is my controller code code:
countryApp.controller('AddLocation', function ($scope, $http) {
$scope.orglocation = {};
//
$scope.submit = function() {
var dataObj = {
location_title : $scope.location.location_title,
location_latitude : $scope.location.location_latitude,
location_longitude : $scope.location.location_longitude
}
//convert data to JSON string
var loc = JSON.stringify(dataObj);
$http.post('http://localhost/slimtest2/add_location', loc).
success(function(data, status, headers, config) {
alert("good");
}).
error(function(data, status, headers, config) {
alert("bye");
});
}
$scope.reset = function() {
$scope.location = angular.copy($scope.orglocation);
}
});
Generally when you hit a CORS problem it is a sign that your server is not configured correctly. I highly suggest looking at the MDN article on HTTP access control. The two headers that are most important to have in this case are:
access-control-allow-origin
access-control-allow-methods
Make sure the first is set to the domain and port you use to access your Angular app and that the second is set to the methods you use (in this case, at least POST).