Calling Webservice From AngularJS - angularjs

I am calling web-service from AngularJS using this code:
$http({
url: "DBService.asmx/GetRG_Users",
dataType: 'json',
method: 'POST',
data: '',
headers: {
"Content-Type": "application/json"
}
But I am only able to access limited number of rows from Service. Once I tried to get all rows it will throw:
500 (Internal Server Error)

Its a server side implementation. You cannot retrieve huge amount of response from the server using http request. You need to set the max size as
php_value post_max_size 20M

I found the solution by using below information in config
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="50000000"/>
</webServices>
</scripting>
</system.web.extensions>

Related

Angular $http.post returns 404 error

I am using angular JS to send some data to Payment Gateway.
Syntax for curl to send data as per documentation is:
curl https://www.mybank.co.uk/3dsecure
-H "Content-type: application/x-www-form-urlencoded"
-X POST
-d 'TermUrl=https://www.yourmerchantsite.co.uk/3DSecureConfirmation&PaReq=value-of-oneTime3DsToken&MD=merchantdatavalue'
However when I am doing it in Angular :
$http({
method: 'POST',
url: 'url',
headers: {'Content-Type': 'application/x-www-form-urlencoded',
'Accept': 'text/html'
},
data: $.param({TermUrl: obj.TermUrl ,Pareq: obj.Pareq }),
})
I am getting error
Possibly unhandled rejection: {"data":"<html><head><title>400 Bad
Request</title></head><body><h1>Bad Request</h1></body>
</html>","status":400,"config":
{"method":"POST","transformRequest":[null],"transformResponse":
[null],"jsonpCallbackParam":"callback","url":"payement gatway
url","headers":{"Content-Type":"application/x-www-form-urlencoded",
"Accept":"text/html,application/xhtml+xml"},"data":"TermUrl=url&Pare
q=value"},"statusText":"Bad Request","xhrStatus":"complete"}
Kindly suggest how to proceed with this one ?
First of all, you are experiencing a 400 Bad Request (https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400) and not a 404 Not Found.
It usually means that you are not sending the right data to the server and the API is expecting some specific parameters (from the body usually).
Check the API, look at every parameter required from it - their types and how they should be sent (body param? query string? etc...).
You can use your browser network tab or tools like Postman to see what you are actually sending to the server and if it matches what the server is expecting you to send.
Check out 3D Secure's API reference, you should get back a detailed error code beside the http status code:
https://developer.paysafe.com/en/3d-secure/api/#/introduction/error-summary/common-errors
It should be easily debuggable.

Google drive api invalid client

I am trying to get access to the google drive content of my users.
I can redeem a code on my domain using the google drive user consent url with correct parameters:
https://accounts.google.com/o/oauth2/v2/auth?response_type=code&client_id='+$scope.googledriveApi.client_id+'&scope='+$scope.googledriveApi.scopes+'&redirect_uri='+$scope.googledriveApi.redirect_uri
I am trying to do an angular $http request to the https://www.googleapis.com/oauth2/v4/token endpoint.
The request looks like this:
$http({
method: 'POST',
headers: {"Content-Type" : "application/x-www-form-urlencoded"},
data: $.param({
"code" : $routeParams.code,
"client_id" : $scope.googledriveApi.client_id,
"client_secret" : $scope.googledriveApi.secret,
"redirect_uri" : $scope.googledriveApi.redirect_uri,
"grant_type" : "authorization_code"
}),
url: 'https://www.googleapis.com/oauth2/v4/token'
})
However the response I get from the request is as follows:
{
"error": "invalid_client",
"error_description": "The OAuth client was not found."
}
Does anyone know why this happens? I have tried changing product name and client id name to be the same. I have checked this for spaces. The reason I'm mentioning this is because this seemed to be the case for other people who asked a question for the same error, however my error happens at the $http request.
I am getting back the user consent code and I am trying to exchange for an access token in this request. This is when the error comes in and I am stuck.
Try these:
Under OAuth consent screen, make sure Product name is not the same with project name as stated in this SO thread:
Try to include an authorization header in your URI request:
headers: { 'Authorization': 'bearer ' + accessToken }

angularJS $http.Post not working: Failed to load resource: Request header field 0 is not allowed by Access-Control-Allow-Headers

I'm using $http to post some data to my data base.
Here is the documentation of the database.
I use it on my terminal and it works.
Here's the error message I got from Safari's console:
1)Failed to load resource: Request header field 0 is not allowed by Access-Control-Allow-Headers. (seems to be sensed by the database)
2)XMLHttpRequest cannot load https://beta-api.mongohq.com/mongo/MyDId/myDatabse/collections/myCollection/documents. Request header field 0 is not allowed by Access-Control-Allow-Headers.
Here's my code:
factory.sendUrlTag = function(data){
d = '{"document" : {"url_URL":"53738eef9256a31f4fdf6bf8","tag_Tag":"537375fc9256a31f4fdf6bf3"} }'
return $http({
url: 'https://beta-api.mongohq.com/mongo/MyDId/myDatabse/collections/myCollection/documents',
method: "POST",
data: d,
headers: [
{'Access-Control-Allow-Origin':'*'},
{'Access-Control-Allow-Headers':'Origin, X-Requested-With, Content-Type, Accept'},
{'Content-Type': 'application/json'},
{'Authorization' : 'api-key MyKey'}
]
})
}
return factory;
};
I didn't have " {'Access-Control-Allow-Origin':'*'},
{'Access-Control-Allow-Headers':'Origin, X-Requested-With, Content-Type, Accept'}," before, but I did some research after I got the error and added these. But it's still not working.
I do $http.get() in my app to the same database and it works.
This thing is driving me nuts....
Please help!
Thank you all! :)
Access-Control-Allow-Origin and friends are response headers, not request headers. It wouldn't make sense if Bob was responsible for granting Bob permission to Alice's system.
The server (https://beta-api.mongohq.com/mongo/MyDId/myDatabse/collections/myCollection/documents) has to send them, not the client.
Since you are making a cross-origin POST request, the server also needs to be able to respond to a pre-flight OPTIONS request.
I found some way maybe able to get around the issue:
Use this and here to get around the cross origin origin issue.
And this to get around the localhost
It may work.
Another relative post.

NetworkError: 405 Method Not Allowed AngularJS REST

In AngularJS, I had the following function, which worked fine:
$http.get( "fruits.json" ).success( $scope.handleLoaded );
Now I would like to change this from a file to a url (that returns json using some sweet Laravel 4):
$http.get( "http://localhost/fruitapp/fruits").success( $scope.handleLoaded );
The error I get is:
"NetworkError: 405 Method Not Allowed - http://localhost/fruitapp/fruits"
What's the problem? Is it because fruit.json was "local" and localhost is not?
From w3:
10.4.6 405 Method Not Allowed
The method specified in the Request-Line is not allowed for the resource
identified by the Request-URI. The response MUST include an Allow header
containing a list of valid methods for the requested resource.
It means the for the URL: http://localhost/fruitapp/fruits The server is responding that the GET method isn't allowed. Is it a POST or PUT?
The angular js version you are using would be <= 1.2.9.
If Yes, try this.
return $http({
url: 'http://localhost/fruitapp/fruits',
method: "GET",
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
I had a similar issue with my SpringBoot project, I was getting the same error in the browser console but I saw a different error message when I looked at the back-end log, It was throwing this error: "org.springframework.web.HttpRequestMethodNotSupportedException, message=Request method 'DELETE' not supported " It turned out that I was missing the {id} parameter in the back-end controller:
** Wrong code :**
#RequestMapping(value="books",method=RequestMethod.DELETE)
public Book delete(#PathVariable long id){
Book deletedBook = bookRepository.findOne(id);
bookRepository.delete(id);
return deletedBook;
}
** Correct code :**
#RequestMapping(value="books/{id}",method=RequestMethod.DELETE)
public Book delete(#PathVariable long id){
Book deletedBook = bookRepository.findOne(id);
bookRepository.delete(id);
return deletedBook;
}
For me, it was the server not being configured for CORS.
Here is how I did it on Azure: CORS enabling on Azure
I hope something similar works with your server, too.
I also found a proposal how to configure CORS on the web.config, but no guarantee: configure CORS in the web.config. In general, there is a preflight request to your server, and if you did a cross-origin request (that is from another url than your server has), you need to allow all origins on your server (Access-Control-Allow-Origin *).

POST data using $resource

DEMO: http://jsfiddle.net/rob_balfre/7QUUf/
How do you POST data (across domain) using $resource?
For example this curl writes to the API with no problem:
curl --dump-header - -H "Content-Type: application/json" -X POST --data '{"name": "Wobbly"}' http://192.168.91.20/api/food/
and the header response is:
HTTP/1.0 201 CREATED
Date: Thu, 25 Oct 2012 08:19:42 GMT
Server: WSGIServer/0.1 Python/2.6.1
Access-Control-Allow-Headers: Content-Type,*
Location: http://localhost/api/food/15/
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST,GET,OPTIONS,PUT,DELETE
Content-Type: text/html; charset=utf-8
I'm totally stuck on how to get angular to POST the same way. This is my $resource, it's worth noting that 'get' works just fine:
angular.module('tastypieModule', ['ngResource']).
factory('FoodOptions', function($resource, $timeout) {
var FoodOptions = $resource('http://testurl/api/:type',
{type: 'food'},
{
get: {method: 'JSONP', params: {format: 'jsonp', callback:'JSON_CALLBACK'}},
update: {method: 'POST', headers: {'Content-Type': 'application/json'}}
}
);
return FoodOptions;
})
When I call update it just fails and I see this is the console network tab:
METHOD: OPTIONS
STATUS: (canceled) Load cancelled
On the server you need to implement a Cross Origin Resource Sharing. http://www.html5rocks.com/en/tutorials/cors/ and http://omarrr.com/cors-html5-approach-to-crossdomain-policies/ both have good articles about the topic. The HEAD request is coming from the browser to your server to check for the headers that contain (or in your case, don't contain) the CORS permissions. If you implement CORS on the server then you'll see the browser first make a HEAD request once to the server then after confirming the correct permissions it will make the POST.

Resources