Issues with calling uber-api products with angularJS - angularjs

I am trying to test out the uber-api products rest endpoint and can't get a successful response using angular. If I paste the $http.get url in the browser it works. However I always get an error response through angularjs. The jsfiddle below is a stripped example of what I'm trying to accomplish.
http://jsfiddle.net/t3kcwc7y/630/
function UberCtrl($scope, $http) {
$http.get('https://sandbox-api.uber.com/v1/products?latitude=37.7759792&longitude=-122.41823&server_token=<token_here>')
.success(function(data) {
console.log('success');
$scope.uberData = data;
})
.error(function(data) {
console.log('error');
$scope.uberData = 'Error: ' + data;
});
}
I was unable to find a existing jsfiddle/plunker example so sorry if this has already been covered. Thanks in advance.
Some side notes, when testing in chrome I get "No 'Access-Control-Allow-Origin' header is present on the requested resource" which appears to be chrome specific CORS error. It works in firefox. My ultimate goal is to execute this from salesforce/force.com and support on any browser. I'm not sure if the CORS error is due to jsfiddle or not.

Please see the example for using the Uber API from the browser with CORS support:
https://developer.uber.com/docs/rides/api-reference
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.uber.com/v1/products?latitude=37.7759792&longitude=-122.41823');
xhr.setRequestHeader("Authorization", "Token YOUR_SERVER_TOKEN");
xhr.send();

Related

Angular http.get + WebApi = Cors failure

on server side I have a C# web api including a controller attributed like this on class level:
[EnableCors(origins: "http://localhost:51664,http://localhost,...", headers: "*", methods: "*")]
I can make ajax calls, e.g. form localhost just fine.
Now I am starting with AngularJS and the http.get-method fails with the following message:
XMLHttpRequest cannot load http://localhost:8081/DividendsManager.Web.Api/api/securities/GetSecurities?yearsDividendsDontDecrease=40. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
This is my AngularJS code:
<script>
var myApp = angular.module('myApp', []);
myApp.controller("myController", function($scope, $http) {
var onSuccess = function(data, status, headers, config) {
$scope.data = data;
};
var onError = function(data, status, headers, config) {
$scope.error = status;
}
var promise = $http.get("http://localhost:8081/DividendsManager.Web.Api/api/securities/GetSecurities?yearsDividendsDontDecrease=40");
promise.success(onSuccess);
promise.error(onError);
});
</script>
In Fiddler, I can see, that the header of the AngularJS-HTTP-Get request has an "Origin: null" entry, which seems to be related to the problem. I think, if instead "null" the value would be "http://localhost", it should work.
Can anyone help me out?
Thank you!
Could it be because in your [EnableCors] attribute, you need to change headers: "", methods: "" to headers: "*", methods: "*"?
Also, you should not include a forward slash at the end of the origins url (if you did).
We had the same issue in our project and we tried so many options as per the suggestions from various web sites. But the thing that worked/working in our case is writing custom CORS provider as mentioned here.
Upppps!
When running in the fresh air today I suddenly was aware why Origin was null. It was, because I was not calling the web site in IIS, but instead I opened the file directly in the file system. For sure, there was no valid URL when doing so, and the Origin was null for the web server.

$http.get success method not called

I am new to AngularJS & NodeJS. I am trying to get a API response from NodeJS and display it in angular. I am using $http to make API call. Below is my nodeJS code.
var express = require('express');
var app = express();
app.get('/employees',function(req,res)
{
console.log("Test Output :");
res.status(200).send('Hello User');
});
app.listen(8080);
Below is my angular code
var myapp = angular.module('myapp',[]).controller('myappController', ['$scope','$http',function ($scope,$http){
$http.get('http://127.0.0.1:8080/employees')
.then(function(response)
{
window.alert("Success");
$scope.emdata=response.data;
},function(errorresponse)
{
window.alert("Error");
$scope.emdata=errorresponse.status;
});
}]);
I am using expression {{emdata}} in HTML page. When I open the HTML page I can see the console output "Test Output " in NodeJS terminal which means the API is getting called but I dont see "Hello User" in HTML page. It looks like the success function in $http.get is not getting called and only the error function is getting called. So I see an alert window with "Error" whenever I open the HTML page and response status as -1 in the place of {{emdata}}.
When I tried making the API call using Postman I get correct response with status 200. So I am wondering what is wrong?
Check headers, i.e. what format is accepted by $http request and the format of the response (JSON, plain text, etc).
Fix value in
$httpProvider.defaults.headers.common
or set needed one in
$httpProvider.defaults.headers.get = { ... };
or just use
var requestParams = {
method: 'GET',
url: '...',
headers: {
...
}
};
$http(requestParams).then(...);
Take a look at Setting HTTP Headers in official manual for more details.

Angular post failing in Chrome

I have the following
function quoteGridController($scope, $http) {
$http.defaults.useXDomain = true;
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
delete $http.defaults.headers.common['X-Requested-With'];
$http.post("http://localhost:57048/service/Quote/ReadQuoteForClientId", $.param({ "ClientId": 2 }))
.success(function (data, status) {
alert("Success");
$scope.status = status;
$scope.data = data;
})
.error(function (data, status) {
alert("Error");
$scope.status = status;
$scope.data = data;
});
}
This call fails when using Chrome but succeeds when using Internet Explorer. From what I have read this is a CORS problem. Is there any way I can get this call to work with both browsers?
EDIT: The Chrome console is giving me the following
XMLHttpRequest cannot load. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Therefore not allowed
access.
As mentioned in the comments above, this is not a client side issue. Chrome do not allow CORS when running from your localhost. A possible solution is to run your web API using a custom domain domain name as explained here.
I however took the easy route and started Chrome with web security disabled, just so that I can test my web API code. Run this from the command prompt
chrome.exe --disable-web-security
Then run your application

angularjs $http post not working with Chrome browser

I'm trying to post an object to my rest service using angularjs.
Unfortunately it isn't working with Google's Chrome browser. Firefox and Internet Explorer work perfectly fine!
Does anyone have an idea what could be the problem?
Heres my Frontend -call:
$scope.saveAssignment = function (cap, aId, wId, hId) {
//all the parameters are strings
var postData = {
assignmentId: aId,
status: "CLOSED",
startDate: new Date(),
endDate: new Date(),
captionText: cap,
workerId: wId,
segment_Id: hId
};
var header ={
'Content-Type': 'application/json; charset=utf-8'
};
$http.post("https://localhost:8443/rest/v1/saveAssignment", postData, header)
.success(function (data, status, headers, config) {
console.log("IN SAVE ASSIGNMENTS - SUCCESS");
console.log(status);
})
.error(function (data, status, headers, config) {
console.log("ERROR!");
//As a response I get data = '' and status = 0
})
}
I have the same problem if I deploy it (independent of localhost or not).
On the server-side (JPA), I'm accepting the call with:
#Path("saveAssignment")
public class SaveAssignment{
#POST
#Consumes(MediaType.APPLICATION_JSON)
public Response saveAss(String assJson) {
System.out.println("TEST");
......
......
}
But not even the print statement "TEST" gets executed...
UPDATE
It looks like it has to be a CORS issue...
Chrome is only sending an OPTION request instead of an POST...
Idea how to fix this?
I already tried
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
but without succes... :(
UPDATE 2
Unfortunately I still don't manage to get it working. So I did a workaround by consciously excluding users with a Chrome browser from doing this post on my page (i.e. seeing the entire page)... (I used it for Amazon's Mechanical Turk, so it's not that severe). But it's not a solution for the origin problem... :-(
To exclude users with Google's Chrome browser I added the following:
$scope.chrome;
$scope.setIsChrome = function(){
var chromium = window.chrome;
var vendorName = window.navigator.vendor;
if(chromium !== null && vendorName === "Google Inc.") {
$scope.chrome = true;
} else {
$scope.chrome = false;
}
}
You have to check additionaly for the vendor name, since the Opera browser return true for "window.chrome" as well...
Is your angular app served via same HTTPS server? If localhost:8433 has self-signed or not matching certificate then that may be your problem as Chrome usually displays security exception page in such case.
Just open any URL starting with https://localhost:8443/ as normal page an then confirm security exceptions. That should help.
Update:
If you use iframe then the embedded page may be restricted by sandbox: http://msdn.microsoft.com/en-us/hh563496.aspx

Web API loads via URL but get Error 404 from Angular script

I have a WebAPI method here:
http://localhost:50463/api/movies
and when accessing it from a browser it loads perfectly.
In my project (the same project as where Web API resides) when calling the method from AngularJS I get an error 500:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
When I click the link in the error it loads the data perfectly.
The routing for WebAPI is as follows:
config.Routes.MapHttpRoute("DefaultApiGet", "Api/{controller}",
new {action = "Get"},
new {httpMethod = new HttpMethodConstraint(HttpMethod.Get)}
);
This is the angular call
app.factory('dataFactory', function ($http) {
var factory = {};
factory.data = function (callback) {
$http.get('/api/movies').success(callback);
};
return factory;
});
I added this javascript just to rule-out angular, I get the same:
$.ajax({
url: "/api/movies",
type: 'GET',
//data: "{ 'ID': " + id + "}",
contentType: "application/json; charset=utf-8",
success: function(data) {
alert(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
});
Any idea what I have done wrong?
I assume your Web API and AngularJS app are running on a different port. In this case you are running in a Same-Origin-Policy issue.
Ensure your Web API is responding with HTTP CORS headers e.g.:
Access-Control-Allow-Origin: http://<angular_domain>:<angular_port>
or
Access-Control-Allow-Origin: *
Doesn't look like a CORS issue to me as you are using a relative URL in your $.ajax() request.
Did you try $.getJSON("/api/movies").then(successHandler, faulureHandler)
Not sure of that will help but for one you are sending a contentType header with a GET request which contains no content. There should be an Accept header instead, but WebAPI should be fine without one.
I would also remove the constrains from the routing and revert back to the default route mapping to see if the problem is there.
config.Routes.MapHttpRoute("DefaultApi",
"api/{controller}/{id}",
new {id = RouteParameter.Optional});

Resources