如何使用 Firebase 和 Angular 发送 HTTP GET 请求?

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

我的应用程序使用 IBM Watson Speech-to-Text,这需要访问令牌。从命令行我可以使用 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"

当我使用 Angular 的 $http 服务发出 HTTP 请求时,出现 CORS 错误:

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");
});

错误消息说:

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.

据我了解,不可能从 Angular 执行 CORS; CORS 必须从服务器完成。我知道如何使用 Node 进行 CORS,但我使用 Firebase 作为服务器。

Firebase documentation 关于使用 CORS 发出 HTTP 请求。文档说要这样写:

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

  });
});

首先,这是行不通的。错误信息是 functions is not defined。显然 functions 不在 Firebase 库中?我从 index.html:

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

我的控制器为 $firebaseArray$firebaseAuth$firebaseStorage 注入依赖项。我需要为 $firebaseHttp 或类似的东西注入依赖项吗?

其次,如何指定方法('GET')、URL、数据(我的帐号和密码)?

如果您想使用 angular 发送凭据,只需设置 withCredentials=true。我也在使用 Angular v4 的 CORS,对于你的 HTTP header 错误,你是对的。 Header Access-Control-Allow-Origin 必须在服务器端添加,请检查您的 api 中是否有设置以允许某些域、网址、页面,因为 google api' s 有这个功能,所以检查你从哪里获得令牌应该有一些设置。

这是示例,我如何使用 CORS 调用 API,使用打字稿:

broadcastPresense(clientId: string) {
    const headers = new Headers({'Content-Type':'application/json','withCredentials':'true'});
    return this.http.post('http://localhost/api.php',
    {
       'jsonrpc': '2.0',
       'method': 'somemethod',
       'params': {'client_id': clientId},
       'id': CommonClass.generateRandomString(16)
    },{headers: headers, withCredentials:true}).map(
        (res: Response) => {
           console.log(res);
           const data = res.json();
           console.log(data);
           if (data.error == null) {
               return data.result;
           } else if (data.error != null) {
              throw data.error;
           }
           throw data.error;
       }
   ).catch(
      (error) => {
         this.router.navigate(['/error',3],{queryParams: {desc:'Server error'}});
         return Observable.throw(error);
      }
   );
}

希望对您有所帮助:)

答案是使用 Cloud Functions for Firebase,它可以从服务器启用 运行 节点功能。然后使用 Node 模块 request 从 Node.

发送 HTTP 请求