代码之家  ›  专栏  ›  技术社区  ›  Josh Simon

Firebase身份验证:如何解决“TypeError:无法读取null”错误的属性“getIdToken”

  •  0
  • Josh Simon  · 技术社区  · 6 年前

    我是实现身份验证的新手,对如何解决我遇到的问题有些困惑。

    我正在构建一个反应应用程序,并希望登录用户能够通过 GigRegister 将组件添加到firebase数据库。然而,当我尝试提交信息时,我收到了以下错误:

    
        TypeError: Cannot read property 'getIdToken' of null
    
    

    您对我如何解决这个问题有什么想法吗?

    这是登录页面的代码(登录后重定向到gig注册页面):

    import React from 'react'
    import Header from './Header'
    import Button from '@material-ui/core/Button'
    import axios from 'axios'
    import {Link} from 'react-router-dom'
    
    class Login extends React.Component {
      constructor() {
        super();
        this.state = {
          email: "",
          password: "",
        };
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
      }
    
      handleChange(e) {
        this.setState({
          [e.target.name]: e.target.value,
        });
      }
    
      handleSubmit(e) {
        console.log("submit reached");
        e.preventDefault();
        const loginData = {
          email: this.state.email,
          password: this.state.password,
        };
        axios("http://localhost:5000/gig-fort/us-central1/api/login", {
          method: "POST",
          headers: {
            "content-type": "application/json",
          },
          data: loginData,
        })
          .then((res) => {
            console.log(res.data);
            this.props.history.push("/gigregister");
          })
          .catch((err) => {
            console.error(err);
          });
      }
    
      render() {
        return (
          <>
            <div>
              <Header />
            </div>
            <Link to="/Homepage" style={{ textDecoration: "none" }}>
              <h1 className="login-header">Gigs this week</h1>
            </Link>
            <div className="login-main">
              <div className="login">
                <h2>Venue login</h2>
                <form onSubmit={this.handleSubmit}>
                  <input
                    type="text"
                    name="email"
                    placeholder="email"
                    onChange={this.handleChange}
                  />
                  <br></br>
                  <input
                    type="password"
                    name="password"
                    placeholder="password"
                    onChange={this.handleChange}
                  />
                  <div className="button">
                    <Button type="submit">Submit</Button>
                  </div>
                </form>
              </div>
              <Link to="/venueregister" style={{ textDecoration: "none" }}>
                <h2 style={{ color: "#b49650" }}>Register a venue</h2>
              </Link>
            </div>
          </>
        );
      }
    }
    
    export default Login;
    

    ..这是gig注册页面:

    
        import React from "react";
        import Header from "./Header";
        import TextField from "@material-ui/core/TextField";
        import Button from "@material-ui/core/Button";
        import axios from "axios";
        import * as firebase from 'firebase'
        
        firebase.initializeApp({
            apiKey: "",
            authDomain: "",
            databaseURL: "",
            projectId: "gig-fort",
            storageBucket: "gig-fort.appspot.com",
            messagingSenderId: "",
            appId: ""
        })
        
        
        class GigRegister extends React.Component {
          constructor() {
            super();
            this.state = {
              name: "",
              venue: "",
              time: "",
              date: "",
              genre: "",
              tickets: "",
              price: "",
            };
            this.handleSubmit = this.handleSubmit.bind(this);
            this.handleChange = this.handleChange.bind(this);
          }
        
          handleChange(e) {
            this.setState({
              [e.target.name]: e.target.value,
            });
          }
        
          handleSubmit(e) {
            console.log("submit function reached");
            e.preventDefault();
            const gigData = {
              name: this.state.name,
              venue: this.state.venue,
              time: this.state.time,
              date: this.state.date,
              genre: this.state.genre,
              tickets: this.state.tickets,
              price: this.state.price,
            };
            
        
            firebase.auth().currentUser.getIdToken().then(function(token) {
              axios("http://localhost:5000/gig-fort/us-central1/api/createGigListing", {
                method: "POST",
                headers: {
                  "content-type": "application/json",
                  "Authorization": "Bearer "+token,
                },
                data: gigData,
              })
          })
              .then((res) => {
                console.log(res.data);
              })
              .catch((err) => {
                console.error(err);
              });
          }
        
        
        
          render() {
            return (
              <div className="gig-register">
                <Header />
                <h1 className="header-gigReg">Register a gig</h1>
                <form onSubmit={this.handleSubmit}>
                  <TextField
                    placeholder="Event name"
                    defaultValue="Event name"
                    id="name"
                    name="name"
                    onChange={this.handleChange}
                  />
                  <TextField
                    placeholder="Venue"
                    defaultValue="Venue"
                    id="venue"
                    name="venue"
                    onChange={this.handleChange}
                  />
                  <TextField
                    placeholder="Time"
                    defaultValue="Time"
                    type="time"
                    label="Enter start time"
                    id="time"
                    name="time"
                    InputLabelProps={{
                      shrink: true,
                    }}
                    inputProps={{
                      step: 300, // 5 min
                    }}
                    onChange={this.handleChange}
                  />
                  <TextField
                    id="date"
                    label="Select date"
                    type="date"
                    defaultValue="2017-05-24"
                    InputLabelProps={{
                      shrink: true,
                    }}
                    onChange={(e) => {
                      this.setState({ date: e.target.value });
                    }}
                  />
                  <TextField
                    placeholder="Genre"
                    defaultValue="Genre"
                    id="genre"
                    name="genre"
                    onChange={this.handleChange}
                  />
                  <TextField
                    placeholder="Tickets"
                    defaultValue="Tickets"
                    id="tickets"
                    name="tickets"
                    onChange={this.handleChange}
                  />
                  <TextField
                    placeholder="Price"
                    defaultValue="Price"
                    id="price"
                    name="price"
                    onChange={this.handleChange}
                  />
                  <Button type="submit">Submit</Button>
                </form>
              </div>
            );
          }
        }
        
        export default GigRegister
    
    

    后端功能:

    app.post('/login', (req,res)=> {
        const user = {
            email: req.body.email,
            password: req.body.password
        }
        
        let errors = {}
    
        if(isEmpty(user.email)){
            errors.email = 'Must not be empty'
        }
    
        if(isEmpty(user.password)){
            errors.password = 'Must not be empty'
        }
    
        if(Object.keys(errors).length >0){
            return res.status(400).json(errors)
        }
    
        firebase.auth().signInWithEmailAndPassword(user.email, user.password)
        .then((data) => {
            return data.user.getIdToken()
        })
        .then(token => {
            return res.json({token})
        })
        .catch(err => {
            if(err.code === 'auth/wrong-password'){
                return res.status(403).json({general: 'Wrong credentials, please try again'})
            }
            return res.status(500).json({error: err.code})
        })
    })
    
    
    2 回复  |  直到 6 年前
        1
  •  2
  •   Alex Mckay    6 年前

    提示

    TypeError: Cannot read property 'getIdToken' of null

    问题

    你写了什么:

    firebase.auth().currentUser.getIdToken()

    编译器正在接收什么:

    null.getIdToken()

    null 没有 getIdToken 因此,当您尝试调用函数时,会得到错误 类型错误:无法读取null的属性“getIdToken” .

    解决方案

    在代码的某个地方,你需要调用 firebase.auth().signInWithEmailAndPassword(email, password) 然后 currentUser 的详细信息保存在浏览器中的 firebaseLocalStorageDB .

    然后,您可以致电 firebase.auth().currentUser.getIdToken() 正确地。

    此外,我不明白你为什么要使用 axios 在这里。您应该使用firebase读/写API,它是 available here 。通读文档,你不会后悔的!

        2
  •  1
  •   Kirill Skomarovskiy    6 年前

    你打电话的原因是什么 signInWithEmailAndPassword 从后端?正如我所见 app.post('/login', ...) 只是验证身体,调用 使用电子邮件和密码登录 并发送令牌作为响应。

    我建议把这个逻辑转移到客户身上。在这种情况下,firebase auth 对象将具有 currentUser .

    如果你不想,你必须打电话 auth.signInWithCustomToken 在客户端发出POST登录请求后。文件: https://firebase.google.com/docs/auth/web/custom-auth#authenticate-with-firebase .

    更新:

    1.创建新文件 firebase.js

    import * as firebase from 'firebase/app'
    import 'firebase/auth'
    /* if you use any other firebase modules import they here.
     * for example:
     * import "firebase/database"
     */
    
    export default function initFirebase() {
      firebase.initializeApp({
        apiKey: '',
        authDomain: '',
        databaseURL: '',
        projectId: 'gig-fort',
        storageBucket: 'gig-fort.appspot.com',
        messagingSenderId: '',
        appId: ''
      })
    }
    
    

    2.从index.js(项目的主文件)初始化应用程序

    import initFirebase from 'path/to/firebase.js';
    // ...imports
    
    initFirebase();
    

    3.将auth导入添加到 Login 组件;

    import React from 'react'
    import Header from './Header'
    import Button from '@material-ui/core/Button'
    import axios from 'axios'
    import { Link } from 'react-router-dom'
    import { auth } from 'firebase/app'
    

    4.将您的提交方式替换为 登录 组件

    handleSubmit(e) {
      e.preventDefault()
      const { email, password } = this.state
      const { history } = this.props
    
      auth().signInWithEmailAndPassword(email, password)
        .then((res) => {
          console.log(res)
          history.push('/gigregister')
        })
        .catch(console.error)
    }
    

    5.在以下位置替换auth导入 GigRegister 组件

    import { auth } from 'firebase/app'
    

    6.在以下位置替换auth调用 GigRegister 组件

    /* handleSubmit method */
    auth().currentUser.getIdToken().then(console.log)
    
        3
  •  0
  •   Aleks    6 年前

    firebase.auth().currentUser 是 null 。您必须在登录页面上登录Firebase。