亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用Express和Javascript通過POST登錄后重定向

使用Express和Javascript通過POST登錄后重定向

米脂 2022-09-02 10:52:28
我正在嘗試構建我的第一個 Node.js 應用程序?,F在我正在一個登錄站點上工作,這應該是在成功登錄后將用戶重定向到/后端。然而,在控制臺中,看起來一切正常,但瀏覽器什么都不做。我在stackoverflow上找到了一些類似的帖子,但大多數人都在使用AJAX,我找不到任何適合我的東西。這是我的POST方法。它首先對用戶進行身份驗證,如果成功,我希望被重定向:router.post('/login', (req, res) => {    store        .authenticate({            username: req.body.username,            password: req.body.password        })        .then(({ success }) => {            if (success) {                res.redirect('/backend')            }            else res.sendStatus(401)        })}); 這是我的后端站點的GET方法:router.get('/', function(req, res, next) {  res.render('backend/backend');}); 不確定是否需要,但下面是觸發 POST 方法的事件列表程序:const Login = document.querySelector('.Login')Login.addEventListener('submit', (e) => {  e.preventDefault()  const username = Login.querySelector('.username').value  const password = Login.querySelector('.password').value  post('/login/login', { username, password })    .then(({ status }) => {      if (status === 200) alert('login success')      else alert('login failed')    })})我的控制臺顯示如下內容:驗證用戶用戶名 POST /login/login 302 GET /backend 304但是,我的瀏覽器不顯示/后端,盡管顯然正在調用GET方法。感謝您的幫助!
查看完整描述

1 回答

?
弒天下

TA貢獻1818條經驗 獲得超8個贊

我不知道函數和選項是什么,但是如果您要將其替換為函數,則可以將屬性設置為在服務器告訴它時重定向。postfetchredirect: 'follow'


const Login = document.querySelector('.Login')

Login.addEventListener('submit', (e) => {

  e.preventDefault()

  const username = Login.querySelector('.username').value

  const password = Login.querySelector('.password').value

  fetch('/login/login', {

    method: 'POST',

    body: JSON.stringify({ username, password }),

    redirect: 'follow'

  }).then(({ status }) => {

    if (status !== 200) alert('login failed')

  })

})

或者,您可以從服務器發送應重定向到的 URL,然后從客戶端手動重定向到該頁面。


// Instead of res.redirect(), use send to send the URL back to the client.

res.send('/backend');

const Login = document.querySelector('.Login')

Login.addEventListener('submit', (e) => {

  e.preventDefault()

  const username = Login.querySelector('.username').value

  const password = Login.querySelector('.password').value

  post('/login/login', { username, password })

    .then((response) => {

      if (response.status === 200) {

        alert('login success');

        return response.text();

      }

      else alert('login failed')

    })

    .then((url) => {

      location.replace(location.origin + url);

    });

})


查看完整回答
反對 回復 2022-09-02
  • 1 回答
  • 0 關注
  • 155 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號