我在前面有一個登錄組件,我在其中對服務器上的路由進行 POST:
const handleSubmit = async (e) => {
e.preventDefault();
try {
fetch("http://localhost:3000/login", {
method: "POST",
mode: "cors",
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
},
body: JSON.stringify({
email,
password,
}),
});
} catch (error) {
console.log(error.message);
}
};
在服務器端,我驗證從前面發送的資訊:
app.post("/login", async (req, res) => {
const user = await Users.findOne({
where: { email: req.body.email, password: req.body.password },
});
if (user) {
console.log(user);
console.log("usuario logeado");
res.status(200).send("LOGGED");
} else {
console.log("Usuario no Registrado");
}
});
一旦我驗證了用戶并知道如何做,我想重定向到前面的組件主頁。
uj5u.com熱心網友回復:
您需要閱讀來自服務器的回應并弄清楚您想用它做什么。我建議不要只從服務器發送一個字串,所以這個解決方案將進行一些重組,希望能幫助您理解和擴展您自己的需求。
// From your server - we're sending some json that we can
// read in the front end code. Maybe you also want to send
// the user object or other data, and json is great for that.
app.post("/login", async (req, res) => {
const user = await Users.findOne({
where: { email: req.body.email, password: req.body.password },
});
if (user) {
console.log(user);
console.log("usuario logeado");
res.status(200).send({
isLoggedIn: true,
});
} else {
console.log("Usuario no Registrado");
res.status(200).send({
isLoggedIn: false,
});
}
});
const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await fetch("http://localhost:3000/login", {
method: "POST",
mode: "cors",
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
},
body: JSON.stringify({
email,
password,
}),
});
// Get the server response as json
const data = await response.json()
if(data.isLoggedIn) {
// Redirect to the account
window.location.href = "/account"
} else {
// Show some error message
window.alert("Invalid login")
}
} catch (error) {
console.log(error.message);
}
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/466371.html
