簡體   English   中英

如何使用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");
});

錯誤消息顯示:

所請求的資源上沒有“ Access-Control-Allow-Origin”標頭。 因此,不允許訪問源' http://127.0.0.1:8080 '。 響應的HTTP狀態碼為401。

據我了解,不可能從Angular進行CORS。 必須從服務器完成CORS。 我知道如何使用Node進行CORS,但我使用Firebase作為服務器。

Firebase具有有關使用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和數據(我的帳戶和密碼)?

如果要發送帶有角度的憑據,只需設置withCredentials=true 我還在Angular v4中使用CORS,對於您的HTTP標頭錯誤,您是對的。 標頭Access-Control-Allow-Origin必須添加到服務器端,請檢查您的api中是否具有允許某些域,URL,頁面的設置,因為google api具有此功能,因此請檢查從哪里獲得令牌應該有一些設置。

這是示例,我如何使用打字稿通過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,它支持從服務器運行節點功能。 然后使用節點模塊request從節點發送HTTP請求。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM