node.js - 注册后重定向失败
问题描述
所以我在用户注册后重定向,我想将他们重定向到主页。这就是我的代码从 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("/");
}
我已经尝试了重定向和位置分配,但它们都没有工作。可能是什么问题呢?
解决方案
如果这是客户端,请尝试window.location.replace
window.location.replace('http://host:port/login');
推荐阅读
- c++ - c++,termios,非规范,阻塞,检测消息结束
- java - setOnClickListener - 如何检测是否在视图之外单击
- flutter - 颤振中sqllite中的多个参数
- laravel - 在您的视图模板中获取控制器和操作名称?
- python - 使用 if 语句减少“玩家”计数
- google-app-engine - App Engine Standard、Serverless VPC、Cloud Memorystore 提供大量超时
- .net-core-3.0 - 如何使用 PipeWriter 读取和更新 HttpResponse 正文?
- php - 显示当前在线人数的实时计数器(PHP 和 jquery)
- asp.net - 在 aspx 网页 (VB) 上显示文件夹中的图像
- google-bigquery - 错误:“表或数据量大于 BI 引擎此时支持的量”