在 Reactjs 中使用 Firebase 电话身份验证时出现“firebaseApp.auth.RecaptchaVerifier 不是构造函数”错误
2020-07-16
2391
我正在从一个文件中导入“firebaseApp”,其中我已完成 firebase 的所有设置,并已实现电子邮件、谷歌和 Facebook 身份验证,但当我实现电话号码身份验证时,ReCaptcha 不是构造函数,我正在使用 ReactJs 功能组件。 有没有办法在没有 ReCaptcha 的情况下实现电话号码身份验证,如果没有,我该如何修复错误。
firebase 的设置
import firebase from 'firebase/app';
import 'firebase/auth'
import 'firebase/firestore';
// Web app's Firebase configuration
var firebaseConfig = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: ""
};
// Initialize Firebase
export const firebaseApp = firebase.initializeApp(firebaseConfig);
export const auth = firebase.auth();
export const db = firebase.firestore();
export const google_provider = new firebase.auth.GoogleAuthProvider();
export const facebook_provider = new firebase.auth.FacebookAuthProvider();
这是我将数字作为用户输入并发送 OTP 进行验证的地方,但示例代码号是硬编码的。
import { firebaseApp, auth } from '../../../firebase/firebasesetup'
function Form() {
const setuprecaptcha = () => {
window.recaptchaVerifier = new firebaseApp.auth.RecaptchaVerifier('recaptcha-container',
{
'size': 'invisible',
'callback': function (response) {
console.log("captcha resolved");
// sendsms();
}
});
}
const sendsms = () => {
setuprecaptcha();
var phoneNumber = '+918220310506';
var appVerifier = window.recaptchaVerifier;
auth.signInWithPhoneNumber(phoneNumber, appVerifier)
.then(function (confirmationResult) {
window.confirmationResult = confirmationResult;
}).catch(function (error) {
alert("not sent")
});
}
return (
<input type="text" placeholder="Mobile" value={mob}
onChange={e => setMob(e.target.value)} />
<div id="recaptcha-container"></div>
<button onClick={sendsms} id='sign-in-button'>Send otp</button>
)
}
export default Form
1个回答
好的,我正在回答我自己的问题。这看起来有点奇怪,但如果你们中的任何人遇到与我相同的问题。
我需要在 firebase_setup 文件中解决 2 件事,并在 React 功能组件中添加主要功能。(总共 3 个更新)
firebase_setup 文件
第一
import firebase from 'firebase';
而不是
import firebase from 'firebase/app';
第二
firebase.initializeApp(firebaseConfig); export const firebaseApp = firebase
React 功能组件
import { firebaseApp} from './firebase_setup';
const sendsms = () => {
//If you want to make the recaptcha invisible
var recaptcha = new firebaseApp.auth.RecaptchaVerifier('recaptcha-container', {
'size': 'invisible'
});
//If you want to make the recaptcha visible
var recaptcha = new firebaseApp.auth.RecaptchaVerifier('recaptcha-container');
//Your phone number with the country code
var number = '+**********';
//actual code begins here
auth.signInWithPhoneNumber(number, recaptcha).then(function (e) {
var code = prompt("enter the code sent to your mobile number");
if (code === null) return;
e.confirm(code).then(function (result) {
alert(result.user + ' verified ')
}).catch(function (error) {
alert('Could not verify,Please try again');
});
}).catch(function (error) {
alert('Please try again.We were unable to reach your phone.Select the correct code and the phone number');
});
}
Priyom saha
2020-07-17