首页 > 解决方案 > 注册后重定向失败

问题描述

所以我在用户注册后重定向,我想将他们重定向到主页。这就是我的代码从 auth 控制器开始的样子

const handleErrors = (err) => {
    console.log(err.message, err.code);
    const errors = {email: "", password: ""};

// duplicate error code
if(err.code === 11000) {
    errors.email = "This email is already in use";
    return errors;}


// validation errors
if(err.message.includes("user validation failed")) {
    Object.values(err.errors).forEach(({properties}) => {
        errors[properties.path] = properties.message;
    })
};
return errors
}

const maxAge = 3 * 24 * 60 * 60;
const createToken = (id) => {
    return jwt.sign({id}, "private key", {expiresIn: maxAge})
}


module.exports.signup_post = async (req, res) => {
const {email, password} = req.body;

try {
    const user = await User.create({email, password});
    const token = createToken(user._id);
    res.cookie("jwt", token, {httpOnly: true, maxAge: maxAge * 1000})
    res.status(201).json({user: user._id});
} catch (err) {
    const errors = handleErrors(err);
    res.status(400).json({ errors });
}

}

然后这是注册路由脚本代码

try {
  const res = await fetch("/signup", {
    method: "POST",
    body: JSON.stringify({email, password}),
    headers: {"Content-Type": "application/json"}
  });
  const data = await res.json();
  console.log(data);

  if(data.errors){
    emailError.textContent = data.errors.email;
    passwordError.textContent = data.errors.password;
  };

  if(data.users){
    res.redirect("/");
    // location.assign("/");
  }

我已经尝试了重定向和位置分配,但它们都没有工作。可能是什么问题呢?

标签: node.jsexpressredirectroutesfetch

解决方案


如果这是客户端,请尝试window.location.replace

window.location.replace('http://host:port/login');

推荐阅读