[英]Axios + reactJS+ passportJS login redirect not working?
I'm trying to implement user authentication for the first time, I can't get the redirect to work after a successful login.我第一次尝试实现用户身份验证,成功登录后我无法让重定向工作。
Function in react: Function 反应:
const login = () => { Axios({ method: "POST", data: { email: loginEmail, username: loginEmail, password: loginPassword, }, withCredentials: true, url: "http://localhost:5000/login", }).then((res) => console.log(res)); };
Backend user controller:后端用户 controller:
exports.login = (req, res) => { const { email, name, username, password } = req.body; const user = new User({ email, name, username }); req.login(user, (err) => { if (err) return next(e); console.log("LOGGED IN") res.redirect('/'); }); };
The console messages do print when I enter a valid user/password, but I just can't get the page to redirect after a successful log in. I've tried using history.push instead of redirecting from the backend, but it would push regardless of whether or not the log in is successful.当我输入有效的用户/密码时,控制台消息会打印出来,但在成功登录后我无法让页面重定向。我尝试使用 history.push 而不是从后端重定向,但它会推送不管登录是否成功。
const login = () => { Axios({ method: "POST", data: { email: loginEmail, username: loginEmail, password: loginPassword, }, withCredentials: true, url: "http://localhost:5000/login", }).then(history.push("/")); };
Does anyone have any insight of why I am unable to redirect from the backend?有没有人知道为什么我无法从后端重定向? How can I better approach this?我怎样才能更好地解决这个问题?
Try this..尝试这个..
const login = async () => {
const res = await Axios({
method: "POST",
data: {
email: loginEmail,
username: loginEmail,
password: loginPassword,
},
withCredentials: true,
url: "http://localhost:5000/login",
});
// if success
history.push("/");
};
In backend user controller instead of res.redirect
send res.send(// if authentication is completed send true, else send false)
.在后端用户 controller 而不是res.redirect
发送res.send(// if authentication is completed send true, else send false)
。
Now you can access this message in then
function.现在您可以在then
中访问此消息。
const login = () => {
Axios({
method: "POST",
data: {
email: loginEmail,
username: loginEmail,
password: loginPassword,
},
withCredentials: true,
url: "http://localhost:5000/login",
}).then((res) => {(res.data===true) && (history.push("/"))});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.