【问题标题】:how to redirect using javascript?如何使用javascript重定向?
【发布时间】:2020-05-17 19:44:35
【问题描述】:

如您所见,我正在使用登录表单在线验证用户和密码,生成令牌,并且一旦令牌存在,应该将用户重定向到pacientes.html 页面。

问题始于renderApp。它确实执行了window.location.href,但为了重定向,我必须手动刷新页面。我做错什么了吗?

let ruta = 'login'

const renderApp = () =>{
    const token = localStorage.getItem('token')
    if (token) {
        window.location.href = "pacientes.html"

    }
}

window.onload= () => {
    renderApp()
    const loginForm= document.getElementById('login')
    loginForm.onsubmit = (e) =>{
        e.preventDefault()
        e.stopPropagation()
        const cedula = document.getElementById('cedula').value
        const password = document.getElementById('password').value

        fetch('https://janfa.gharsnull.now.sh/api/auth/login', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({cedula, password})
        }).then( x => x.json())
          .then( respuesta => {
            localStorage.setItem('token' , respuesta.token)
            ruta = 'users'
          })
    }

}  

【问题讨论】:

  • 所以 url 改变了但页面没有重新加载?

标签: javascript html token window.location


【解决方案1】:

如果您想在收到 HTTP 请求的响应时进行重定向,请将要重定向的代码放在 then 回调中。

即将ruta = 'users' 替换为location.href = "pacientes.html"

如果你把它放在渲染函数中,它只会在组件渲染时执行!

【讨论】:

  • 天哪,非常感谢。我只是在学习js,这种事情对我来说有点困难
猜你喜欢
  • 2020-12-06
  • 2012-03-27
  • 2016-10-12
  • 1970-01-01
  • 2016-01-20
  • 2012-07-26
  • 1970-01-01
相关资源
最近更新 更多