2016-07-23 191 views
0

我开始学习如何在我的应用中使用Firebase。我按照角网站的指令,并设置片段像中的index.html:HTTP请求:PUT 401(未授权)

<!-- The codes to add firebase --> 
    <script src="https://www.gstatic.com/firebasejs/3.2.0/firebase.js"></script> 
    <!-- The core firebase client (required) --> 
    <script src="https://www.gstatic.com/firebasejs/3.1.0/firebase-app.js"></script> 
    <!-- firebase-auth - Firebase Authentication (optional) --> 
    <script src="https://www.gstatic.com/firebasejs/3.1.0/firebase-auth.js"></script> 
    <!-- firebase-database - The Firebase Realtime Database (optional) --> 
    <script src="https://www.gstatic.com/firebasejs/3.1.0/firebase-database.js"></script> 

    <script> 
    var config = { 
     apiKey: ..., 
     authDomain: ..., 
     databaseURL: "https://...", 
     storageBucket: "...", 
    }; 
    firebase.initializeApp(config); 
    </script> 

然后我尝试使用HTTP请求,把数据,如:

submitForm(personalInfo: PersonalInfo, educationsInfo: Education[], experiencesInfo: Experience[]): Observable<string>{ 
    let body = JSON.stringify({personalInfo, educationsInfo, experiencesInfo}); 
    let headers = new Headers({'Content-Type': 'application/json' }); 
    let options = new RequestOptions({ headers: headers}); 
    console.log(body); 
    let url = this.firebaseUrl + 'apply-form.json'; 
    return this.http.put(url, body) 
        .map((response) => { 
         return response; 
        }) 
        .catch(this.handleError); 
} 

但是,我得到了以下错误:

PUT https://XXX.firebaseio.com/apply-form.json 401 (Unauthorized) 

我不知道是什么问题。我是使用Firebase的新人,真的需要有人来帮助我。谢谢!

回答

1

您的Firebase数据库默认情况下只能由经过身份验证的用户写入。请参阅saving data to the database页面上第一个蓝色框中的警告。

要解决此问题,您当然可以使用configure the security rules of your database to allow public access。但是,虽然在开发过程中这通常很好,但当您的应用程序准备好发布给除您自己以外的人员时,这是一个糟糕的主意。

安全发布数据的正确方法是要求用户登录sign in with Firebase Authentication,然后使用该信息确保他们只能访问他们授权的数据。通过使用HTTP访问Firebase数据库,您已经使自己比需要的更加困难。我建议您为authentication和访问database使用Firebase JavaScript SDK。

+0

谢谢你的回应。我认为这可能是权威问题,但我没有如何解决它。它在我更改安全规则后生效。但我会听取您的建议,尝试使用Firebase SDK。非常感谢 :) – gogopower

相关问题