Thomas David Kehoe Thomas David Kehoe - 1 year ago 120
AngularJS Question

How to send an HTTP GET request using Firebase and Angular?

My app uses IBM Watson Speech-to-Text, which requires an access token. From the command line I can get the access token with curl:

curl -X GET --user my-user-account:password \
--output token \
"https://stream.watsonplatform.net/authorization/api/v1/token?url=https://stream.watsonplatform.net/speech-to-text/api"


When I make an HTTP request using Angular's
$http
service I get a CORS error:

var data = {
user: 'my-user-account:password',
output: 'token'
};

$http({
method: 'GET',
url: 'https://stream.watsonplatform.net/authorization/api/v1/token?url=https://stream.watsonplatform.net/speech-to-text/api',
data: data,
}).then(function successCallback(response) {
console.log("HTTP GET successful");
}, function errorCallback(response) {
console.log("HTTP GET failed");
});


The error message says:


No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://127.0.0.1:8080' is therefore not allowed
access. The response had HTTP status code 401.


As I understand, it's not possible to do CORS from Angular; CORS has to be done from the server. I know how to do CORS with Node but I'm using Firebase as the server.

Firebase has documentation about making HTTP requests with CORS. The documentation says to write this:

$scope.getIBMToken = functions.https.onRequest((req, res) => {
cors(req, res, () => {

});
});


First, that doesn't work. The error message is
functions is not defined
. Apparently
functions
isn't in the Firebase library? I call Firebase from
index.html
:

<script src="https://www.gstatic.com/firebasejs/4.3.0/firebase.js"></script>


My controller injects dependencies for
$firebaseArray
,
$firebaseAuth
, and
$firebaseStorage
. Do I need to inject a dependency for
$firebaseHttp
or something like that?

Second, how do I specify the method ('GET'), the URL, and the data (my account and password)?

Answer Source

The answer is to use Cloud Functions for Firebase, which enable running Node functions from the server. Then you use the Node module request to send the HTTP request from Node.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download