首页 > 解决方案 > 登录系统在 Postman 中正常工作,但在浏览器中不能正常工作

问题描述

这是我的路由器

 router.post("/login", async (req, res) => 
    {
        try
        {
            const user = await User.findByCredentials(req.body.email, req.body.password)  
            // console.log(user)
            const token = await user.generateAuthToken()
            // console.log(token)
            res.redirect("/takvim")
        }
        catch(e)
        {
            res.status(400).redirect("/")
        }
    })

这是我在上面的函数中使用的用户模型

UserSchema.methods.generateAuthToken = async function () 
{
    const user = this
    const token = jwt.sign({_id: user._id.toString()}, "secret")
    user.tokens = user.tokens.concat({token})
    await user.save()
    return token
}

UserSchema.statics.findByCredentials =  async function (emails, passwords)
{    
  const user = await User.findOne({email: emails})
  console.log(user)
  const isMatch = await bcrypt.compare(passwords, user.password)
  if(!isMatch)
  {
    throw new Error("unable to login")
  }
  return user   
}

我正在使用按钮从前端发出请求

$uyeolForm.addEventListener("submit", () => 
{
    if(!$uyeolFormEmail.value.includes(".com"))
    {
       return $uyeolFormHata.innerHTML = "email geçersiz" 
    }
    const xhr = new XMLHttpRequest();
    let form = JSON.stringify({
    email: $uyeolFormEmail.value,
    password: $uyeolFormPassword.value
    });
    xhr.open("POST", "/login")
    xhr.setRequestHeader('Content-type', 'application/json')
    xhr.send(form);
})

问题是当我使用邮递员时,应用程序将我重定向到我想要的页面并且没有给出错误。当我使用按钮发送请求时,它仍然可以找到用户,但它没有将我重定向到我期望的页面,并且在控制台中我看到了用户(预期),null这是不期望的。

谢谢大家。

标签: javascriptnode.jsmongodbmongoosepostman

解决方案


当触发事件时,您正在使用 XMLHttpRequest 发出 HTTP 请求,submit但您并没有阻止表单提交的默认行为。

因此,创建 XMLHttpRequest 对象并发出请求,然后立即(可能会根据事情进展的速度取消请求)将<form>其提交到action.

您说端点被击中了两次,一次是您获得期望的用户,一次是您没有获得的用户。

当您获得您期望的用户时,它来自 XHR 提交。

如果您不这样做,那就是来自常规表单提交(不会被 JSON 编码为 HTML 表单不支持 JSON 编码,因此它找不到用户,因为它没有正确解码表单中的数据)。


既然您说要重定向,请不要使用 AjaxAjax 是一种在不离开当前页面的情况下发出 HTTP 请求的方法。

更改服务器端代码以接受<form>编码格式的数据(可能application/x-www-form-urlencoded除非您使用enctype属性更改它)。


推荐阅读