Reputation: 301
I'm attempting to use the Uber API in my JavaScript client.
I'm aware that this involves CORS, since my client will be accessing the Uber API directly via AJAX.
In the Uber Developers Dashboard, I set my Origin URI correctly. Then, I set up the most simple example I could find. This came from Uber's docs:
<!DOCTYPE html>
<html>
<head>
<title>Uber API Demo</title>
</head>
<body>
<script>
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.uber.com/v1.2/products?latitude=37.7759792&longitude=-122.41823');
xhr.setRequestHeader("Authorization", "Token <ServerToken>");
xhr.send();
</script>
</body>
</html>
Looking at the Console in Chrome Dev Tools, this is what I see:
And, most interesting, the Network tab:
My browser is changing my HTTP POST into an HTTP OPTIONS request (part of the CORS preflight defined in the fetch spec), which it looks like Uber does not support. Uber's server should reply with the response headers, authorizing my client to finish its API request. Instead, they are returning a 404.
In summary:
Anyone know what's going on here?
Upvotes: 1
Views: 3091
Reputation: 88235
When making requests to Uber API endpoints from frontend JavaScript code running in a browser, instead of adding an Authorization
header to the request, you need to add an access_token
query parameter to the request URL, like this:
https://api.uber.com/v1.2/products?access_token=<TOKEN>&latitude=XXX&longitude=XXX
See https://developer.uber.com/docs/trip-experiences/guides/authentication#use-bearer-token
Uber's docs say they support CORS
Yeah, the docs aren’t completely accurate in making that claim.
My browser is changing my HTTP POST into an HTTP OPTIONS request…
To be more precise: The browser’s not changing the POST
into an OPTIONS
; instead the browser’s doing an OPTIONS
request before trying your POST
request. And the reason the browser’s doing that is because your code adds an Authorization
header to the request.
(part of the CORS preflight defined in the fetch spec), which it looks like Uber does not support
Right. And that’s where the claim in the Uber API docs that they support CORS isn’t completely accurate. They don’t actually fully support CORS; specifically, their API endpoints don’t support handling of CORS preflight OPTIONS
requests at all.
And adding an Authorization
header to a request from frontend JavaScript running in a browser causes the browser to do a preflight OPTIONS
request.
So because the Uber API endpoints don’t support that, you can’t make requests from frontend JavaScript code to Uber API endpoints using an Authorization
request header to provide the credentials. You need to instead add the access_token
query parameter to the request URL.
Upvotes: 1