Angularjs - 500 (Internal Server Error) on $http Post - angularjs

I am new to Ionic and angular. I am building a sample with ionic framework using angular.js. I want to call WebApi through $http post method. I checked this(ionic-proxy-example) solution and I am trying to implement the same using my api. When I call the api provided in above example in my sample project, I get the records but its not working with my api. It throws 500 internal error.
Here is my app.js
angular.module('myApp', ['myApp.controllers', 'myApp.services'])
.constant('ApiEndpoint', {url: 'http://localhost:8100/api'})
Services.js
angular.module('myApp.services', [])
.factory('Api', function($http, $q, ApiEndpoint) {
console.log('ApiEndpoint', ApiEndpoint)
var getApiData = function() {
var q = $q.defer();
var data = {
Gameweek_ID: '179',
Vender_ID: '1',
Language:'en'
};
var config = {
headers : {
"Content-Type": "application/json; charset = utf-8;"
}
};
$http.post(ApiEndpoint.url, data, config)
.success(function (data, status, headers, config) {
// $scope.PostDataResponse = data;
alert('success');
console.debug("response :" + data);
q.resolve(data);
})
.error(function (data, status, header, config) {
// $scope.ResponseDetails = "Data: " + data +
alert('error');
console.debug("error :" + data);
q.reject(data);
});
return q.promise;
}
return {getApiData: getApiData};
})
controllers.js
angular.module('myApp.controllers', [])
.controller('Hello', function($scope, Api) {
$scope.employees = null;
Api.getApiData()
.then(function(result)
{console.log("result is here");
jsonresponse = result.data;
$scope.employees = jsonresponse;}
)
});
And Ionic.Project File
{
"name": "Multilingual",
"app_id": "4b076e44",
"proxies": [
{
"path": "/api",
"proxyUrl": ""
}
]}
I am trying to understand the problem and checked multiple methods to call the api. Surprisingly, it works with ajax post call without any CORS errors. As I am using Angular, I am trying to get this done through $http post. I feel it is some minor issue but I am not able to figure out. Will be grateful for solutions. Thank you.

You've set the content type to json so the sever is expecting a json string but isn't receiving a properly formatted json string as you're sending through an object and hence the error.
Where you have $http.post(ApiEndpoint.url, data, config) change it to $http.post(ApiEndpoint.url, JSON.stringify(data), config).
If that doesn't work, change your content type to application/x-www-form-urlencoded and update this line $http.post(ApiEndpoint.url, data, config) to $http.post(ApiEndpoint.url, $httpParamSerializer(data), config) , don't forget to inject the $httpParamSerializer function.

The problem is that you are sending a POST with $http.post request instead of a GET request with $http.get

Try as below-
$http({
url: ApiEndpoint.url,
method: "POST",
data: data,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).Success(..rest code goes here..)
In WebAPI, when we pass more than one object in POST method, we get 500 internal error and hence we use ViewModel in such scenarios(talking about asp.net MVC).

Related

Retrieve a Sharepoint List with Angular JS

I have created an Angular JS application which would output a list of data in a Share Point list. I am trying to make a rest API call to my Share Point List to get the data, however I am unable to do it as I get an error 403 Forbidden.
Below is my controller which tries to fetch the data.
app.controller('RetrieveRecords', function ($q, $http, $scope) {
var url = "https://testapp.sharepoint.com/sites/testmyapplication/_api/web/lists/getByTitl
e('TestAppList')/items?$select=Status,Time";
$http(
{
method: "GET",
url: url,
headers: { "accept": "application/json;odata=verbose" }
}
).success(function (data, status, headers, config) {
$scope.details = data.d.results;
}).error(function (data, status, headers, config) {
});
});
My Angular JS application is not a Share Point page, my application is basically hosted as a Azure Static Website. I checked some online tutorials, however I couldn't find a solution to the problem I am facing.
Thank you.
#John,
You have to supply digest within the header.
You will find the necessary value in the element called '__REQUESTDIGEST'. So with jQuery you can get the value like this: $('#__REQUESTDIGEST').val().
This value needs to be added to the header:
headers: { "Accept": "application/json;odata=verbose", "X-RequestDigest": $('#__REQUESTDIGEST').val() }
can you try adding this tag and see if it works.
Hope it helps.
MV

angular laravel nginx 400 Bad Request

Help, I've got 400 error on POST and or PUT method, but GET works just fine,
I'm using angular as front end and laravel as API, my server is using nginx,
I've used CORS and I everything works fine on my local vagrant which is running on apache.
I'm sure I have my route set correctly, here's some of it from the module I use:
Route::group(array('prefix'=>'/api', 'middleware' => 'cors'),function(){
Route::post('/create_level', 'LevelController#store');
Route::get('/read_level', 'LevelController#index');
Route::get('/read_level/{id}', 'LevelController#show');
Route::put('/read_level/{id}', 'LevelController#update');
Route::delete('/read_level/{id}', 'LevelController#destroy');
here's part of my angular service:
app.service("edulevelService", function ($http, $q, $rootScope)
{
edu.updateEdulevel = function(id, edu){
var deferred = $q.defer();
$http.put($rootScope.endPoint + 'read_level/'+ id, edu)
.success(function(res)
{
deferred.resolve(res);
})
.error(function(err, stat){
deferred.reject(err);
console.log('error code: Ser-UEDU');
});
return deferred.promise;
}
edu.createEdulevel = function(edu){
var deferred = $q.defer();
$http.post($rootScope.endPoint + 'create_level', edu)
.success(function(res)
{
deferred.resolve(res);
})
.error(function(err, stat){
deferred.reject(err);
console.log('error code: Ser-CEDU');
});
return deferred.promise;
}
....
oh I forgot to mention different method cause different error code POST cause 405, PUT cause 400, and I've tried using Postman:
POST is working using text type and return 405 using application/json,
but when I tried
PUT method even though it return 200 I only got NULL data entered to my db (text type), and if I use application/json it return 400
Please Help
Finally found solution:
change $http.post to:
$http({
method: "post",
url: $rootScope.endPoint + 'create_level',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param({ .... })
})
somehow it works, exept on my login page which using stellizer to do post method and i can't find how should I change it without breaking all the function...
any one?
I only need to add:
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
and
data: $.param({ ...... })

Angular REST cannot return simple data

I am trying to get a $http REST GET call working in my Appgyver project working but nothing I do seems to come right, always returns an error.
Please note the angular app will be running on mobile devices eventually and then connect to my remote web service.
I've double checked that my custom API is working and returning data correctly in a number of ways, namely:
hard coded cUrl request running from sh files in terminal - Returns data and correct 200 code
Tested the API end points in both POSTMAN and Firefox's SOA client.
Putting in my test end point of http://somesite.com/quote-and-buy-performance/druidapi/taxonomy_term returns data as below:
[{"tid":"1","vid":"2","name":"ACME Ltd.","description":"","format":"filtered_html","weight":"0","parent":"0","uri":"http://somesite.com/quote-and-buy-performance/druidapi/taxonomy_term/1"},{"tid":"2","vid":"2","name":"ABC Films LTD","description":"","format":"filtered_html","weight":"0","parent":"0","uri":"http://somesite.com/quote-and-buy-performance/druidapi/taxonomy_term/2"}]
Even a simple CSRF Token request gives me errors.
Could someone possibly point out where I am going wrong here, the Appgyver site is badly documented and I have tried the Angular RESTful sample which my code below is based upon from https://docs.angularjs.org/api/ng/service/$http and https://docs.angularjs.org/api/ng/service/$http#setting-http-headers
Please note the code below is basically Angular.js using Javascript syntax (as opposed to Coffeescript), logging output follows the code
angular
.module('main')
.controller('LoginController', function($scope, supersonic, $http) {
$scope.navbarTitle = "Settings";
$scope.stoken = "Response goes here";
$scope.processLogin = function(){
var csrfToken;
steroids.logger.log("START CALL: processLogin");
// $form_login_email_address = $scope.login_email;
// $form_login_password = $scope.login_password;
$local_get = "http://somesite.com/quote-and-buy-performance/services/session/token";
$hal_get_taxterm_index = "http://somesite.com/quote-and-buy-performance/druidapi/taxonomy_term";
// $http.defaults.headers.common.contentType('application/json');
var req = {
method: 'GET',
url: $hal_get_taxterm_index,
headers: {
'Content-Type': 'application/json'
}
}
$http(req)
.success(function(data, status, headers) {
steroids.logger.log("Inside http.get() success");
}).error(function(data, status, headers){
steroids.logger.log("Inside http.get() WITH ERROR");
steroids.logger.log('data: ' + data);
steroids.logger.log('status: ' + status);
}).then(function(data, status, headers){
steroids.logger.log("Inside http.get() then");
});
steroids.logger.log("END CALL: processLogin");
}
});
Logging output from calls to steroids.logger.log
View Time Level Message
main#login 16:01:55.219 info "Inside http.get() WITH ERROR"
main#login 16:01:55.219 info "data: null"
main#login 16:01:55.219 info "status: 0"
main#login 16:01:55.64 info "END CALL: processLogin"
main#login 16:01:55.64 info "START CALL: processLogin"
Here's what I would do:
Separate out your http call into a service. This is a pretty standard way to modularize your code in angular:
angular.module('main').factory("SomeService", function($http) {
return {
get: function() {
$http({
url: "http://somesite.com/quote-and-buy-performance/druidapi/taxonomy_term",
method: "GET",
headers: {
"Content-Type": "application/json"
}
}).success(function(data, status, headers, config) {
console.log("Success!");
console.log(data);
}).error(function(data, status, headers, config) {
console.log("Error!");
console.log(status);
console.log(data);
});
}
}
})
Then to use this in your controller, just include it in your controller declaration and call get like you would a normal method:
angular.module('main').controller('LoginController', function($scope, supersonic, SomeService) {
$scope.navbarTitle = "Settings";
$scope.stoken = "Response goes here";
$scope.processLogin = function(){
var csrfToken;
steroids.logger.log("START CALL: processLogin");
SomeService.get();
steroids.logger.log("END CALL: processLogin");
}
})
Do this and then comment back with your results and we can work from there.
If your angular's app is within a certain domain, then HTTP request must be made within the same domain.
In your case, you are trying a cross domain request (a request on another domain). You must then make a cross domain request.
You can see this question.
The author uses $http.jsonp() to send cross domain requests. There migth be another way to do it.

Angular http call fails with content-type json

Here is my service:
home.factory("homeService", function ($http, $q) {
var service =
{
getAssets: function () {
var deferred = $q.defer();
var response = $http({
method: "post",
dataType: "json",
data: '',
headers: {
'Content-Type': "application/json"
},
url: "http://localhost/myWeb/services/reports_ws.asmx/getData",
});
response.success(function (data) {
deferred.resolve(data);
});
response.error(function (data) {
alert('Error');
});
// Return the promise to the controller
return deferred.promise;
},
}
return service;
I am getting 500 error from the server when I use application/json for the content. using plain/text works fine and data is returned, but in an xml format although the server sends data back in json format. I have tested it in Chrome, everything works fine. I also noticed that Chrome sends request using "application/x-www-form-urlencoded" for content-type. I tried it too, but still got data in xml. Please help.
Thanks
keep trying with the following:
header: { "Content-Type" : "application/x-www-form-urlencoded"}
Please notice that this applies only for the header of the request, not the response. The response depends on your backend (server side).
Several ways are available to return JSON data in the response depending of the type of server you are using.

When setting http authorization headers the AngularJS app crashes

I want to make a request to the twitter api and get the current logged in userfeed.
I tryed the twitter api with "apigee" and everything works fine. Even when copying the Authorization header from "apigee" into "postman" I get back data.
Well but when I try to make the http-request in my angular-app, the whole app stops working.
In the browser there ist just the output "{{message}}" and the console prints two error messages:
Uncaught SyntaxError: Unexpected identifier :3000/javascripts/app.js:211
Uncaught Error: No module: app angular.min.js:17
The code in my app looks like this
app.controller('TwitterCtrl', function($scope, $http) {
var url = "https://api.twitter.com/1.1/statuses/home_timeline.json";
$http.get(url,
{headers: {
'Authorization':
Oauth oauth_consumer_key = "xxxx",
oauth_signature_method="HMAC-SHA1"
oauth_timestamp="1401883718",
oauth_nonce="840988792",
oauth_version="1.0",
oauth_token="xxxx",
oauth_signature="xxx"
}})
.then(function (data) {
$scope.data = data.data;
console.log(data);
});
Can anyone help me or tell me what I'm doing wrong.
Kevin
try this way:
app.controller('TwitterCtrl', function($scope, $http) {
var url = "https://api.twitter.com/1.1/statuses/home_timeline.json";
$http.get(url, {
headers: {
'Authorization':
'Oauth oauth_consumer_key = "xxxx",' +
'oauth_signature_method="HMAC-SHA1",' +
'oauth_timestamp="1401883718",' +
'oauth_nonce="840988792",' +
'oauth_version="1.0",' +
'oauth_token="xxxx",' +
'oauth_signature="xxx"'
}
}).then(function (data) {
$scope.data = data.data;
console.log(data);
});

Resources