【发布时间】:2021-09-13 18:11:15
【问题描述】:
我的后端向我的前端发送 res.staus(200).json({somedata)},但我无法在前端检索数据。
我的后台:
exports.login = (req, res, next) => {
//===== Check if user exists in DB ======
const { user_email, user_password: clearPassword } = req.body;
let sql = `SELECT user_password, user_id FROM users WHERE user_email=?`;
db.query(sql, [user_email], async (err, results) => {
console.log(results);
console.log(req.body);
if (err) {
return res.status(404).json({ err });
}
// ===== Verify password with hash in DB ======
const { user_password: hashedPassword, user_id } = results[0];
try {
const match = await bcrypt.compare(clearPassword, hashedPassword);
if (match) {
console.log("match ... user_id : ", user_id);
// If match, generate JWT token
res.status(200).json({
test: 'iyu',
user_id: user_id,
token: jwt.sign({ userId: user_id }, "TOOOKEN", {
expiresIn: "24h",
}),
});
} else {
console.log("not match");
}
} catch (err) {
return res.status(400).json({ err: "une erreur" });
}
});
};
前端:
const login = async (e) => {
e.preventDefault();
await POST(ENDPOINTS.USER_LOGIN, userLogin);
// await GET(ENDPOINTS.USER_LOGIN)
fetch("http://localhost:4200/api/auth/login")
.then((response) => response.json())
.then((data) => {
console.log(data);
});
};
此登录功能将数据发送到我的后端,然后后端使用第一个 POST 请求检查数据库中是否存在用户。如果是,后端以 json 格式发送一些我不想放在用户本地存储中的数据,所以在 POST 请求之后,我使用 GET 方法执行另一个请求以检索从后面发送的 json 数据,但是我遇到了 404 错误。
我怎样才能让我的数据被后台发过来?
【问题讨论】:
-
您没有在 GET 请求中发送任何参数。后端应该如何知道您要检索哪个用户?此外,您的后端函数期望在
req.body中找到用户的凭据,但获取请求中没有正文。