登录后重定向

时间:2018-02-16 20:17:22

标签: javascript node.js express

我是开发人员的网络端(一直在做移动设备),我正在使用firebase.auth()来签署用户。我想知道我应该如何构建我的页面重定向到我的javascript /节点。

任务完成后,指向新页面的正确js代码是什么?

我正在尝试的代码看起来像这样

btnLogin.addEventListener('click', e => {

    console.log("hey");

    const email = txtEmail.value;
    const pass = txtPassword.value;
    const auth = firebase.auth();

    //Sign In
    const promise = auth.signInWithEmailAndPassword(email, pass);
    promise.catch(e => console.log(e.message));
    window.location="/index3.html"
  });

正在运行的解决方案代码:

btnLogin.addEventListener('click', e => {

    console.log("hey");

    const email = txtEmail.value;
    const pass = txtPassword.value;
    const auth = firebase.auth();

    //Sign In
    // const promise = auth.signInWithEmailAndPassword(email, pass);
    // promise.catch(e => console.log(e.message));
   //  window.location="/index3.html"
   auth.signInWithEmailAndPassword(email, pass)
        .then(function() {
            window.location.href = "/aftersign";
            // window.location.assign("/index3");
        })
        .catch(function(e) {
        console.log(e.message);
    });
  });

我有一个单独的.js文件定义我的重定向所以/ aftersign重定向到index3.html。

1 个答案:

答案 0 :(得分:2)

通过定位承诺"成功"来尝试以下方法。 Firebase方法then()返回的承诺的处理程序signInWithEmailAndPassword()signInWithEmailAndPassword()是一个返回Promise的异步操作。现在,通过如何构建代码,重定向可以在signInWithEmailAndPassword()完成之前以及发生错误时发生。在window.location内执行.then()分配可确保在任何重定向操作发生之前登录成功。

您可以使用assign(somePath)window.location方法或设置window.location.href的值。

btnLogin.addEventListener('click', e => {
    const email = txtEmail.value;
    const pass = txtPassword.value;
    const auth = firebase.auth();

    //Sign In
    auth.signInWithEmailAndPassword(email, pass)
        .then(() => window.location.href = "/index3" /* window.location.assign("/index3") */)
        .catch(e => console.log(e.message));
});

根据浏览器的目标定位,lambda语句如`e => console.log(e.message)可能不可用,而是看起来像:

btnLogin.addEventListener('click', e => {
    const email = txtEmail.value;
    const pass = txtPassword.value;
    const auth = firebase.auth();

    //Sign In
    auth.signInWithEmailAndPassword(email, pass)
        .then(function() {
            window.location.href = "/index3";
            // window.location.assign("/index3");
        })
        .catch(function(e) {
            console.log(e.message);
        });
});

希望这有帮助!