【问题标题】:Why am i not able to redirect to my get router when fetched with a post request?为什么在使用 post 请求获取时我无法重定向到我的 get 路由器?
【发布时间】:2020-07-29 14:28:21
【问题描述】:

profile.ejs

<body>
    <div id="box">
        <h1>Hello, <span><%= user.name %></span>!<hr> How are you doing?</h1>
        <!-- <form action="/users/logout" method="POST"></form> -->
            <button onclick="logout()">LOGOUT</button>
        <!-- </form> -->
    </div>

    <script>

        var userToken = document.cookie.replace('jwt=','')
        // console.log(document.cookie)
        // console.log(userToken)

        function logout()
        {
            fetch('/users/logout', {
                method: 'POST',
                headers: {
                'Authorization': 'Bearer ' + userToken
                },
                redirect: 'follow'
            })
            // .then(res => res.json())
            .then(response=>{
                    if (response.redirected) {
                        window.location.href = response.url;
                    }
            })
            .catch(err => { console.log(err) })
        }
        
    </script>
</body>

app.js

app.post('/users/logout' ,async(req,res)=>{
    try{
        req.user.tokens = req.user.tokens.filter((token)=>{return token.token!=req.token})
         await req.user.save()
        // res.status(200).send({message:'Logged Out Successfully!'})
        console.log('Logged Out Successfully!')
        res.redirect('/')
  
    }catch(e){
        res.status(400).send(e)
    }
})
app.get('/',(req,res)=>{
    res.render('index')
    console.log('ok')
})

令人惊讶的是,我从第二个路由器收到消息“ok”。但是我没有重定向到它!网址不变! 有人请帮我解决这个问题。我被困在这里很久了!

【问题讨论】:

    标签: javascript node.js authentication redirect


    【解决方案1】:

    您应该使用window.location.pathname 而不是window.location.href

    【讨论】:

    • 我不知道怎么做,但我重新启动了我的电脑,却发现程序运行得非常完美!但是,你能解释一下你为什么这么建议吗?
    • pathname(它的建议方式)仅用于路径地址,href 用于完整的 URL 域 + 路径
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-24
    • 2011-05-21
    • 2019-12-07
    • 1970-01-01
    • 2020-12-11
    • 2021-09-02
    • 1970-01-01
    相关资源
    最近更新 更多