export const deletePost = (req, res) => {
const token = req.cookies.token;
if (!token) return res.status(401).json("Not authenticated!");
jwt.verify(token, "jwtkey", (err, userInfo) => {
if (err) return res.status(403).json("Token is not valid!");
const postId = req.params.id;
const q = "DELETE FROM posts WHERE `id` = ? AND `uid` = ?";
db.query(q, [postId, userInfo.id], (err, data) => {
if (err) return res.status(403).json("You can delete only your post!");
return res.json("Post has been deleted!");
});
});
};
上面的代码是我的删除功能控制器
export const login = (req, res) => {
//CHECK USER
const q = "SELECT * FROM users WHERE username = ?";
db.query(q, [req.body.username], (err, data) => {
if (err) return res.status(500).json(err);
if (data.length === 0) return res.status(404).json("User not found!");
//Check password
const isPasswordCorrect = bcrypt.compareSync(
req.body.password,
data[0].password
);
if (!isPasswordCorrect)
return res.status(400).json("Wrong username or password!");
const token = jwt.sign({ id: data[0].id }, "jwtkey");
const { password, ...other } = data[0];
console.log(token)
res
.cookie("token", token, {
httpOnly: true,
secure: false
})
.status(200)
.json(other);
});
};
上面的代码用于登录
我的问题是,当我登录时,cookie似乎设置正确,因为当我从登录函数控制台记录令牌时,令牌正在打印,但当我使用deletepost函数打印令牌时,它返回未定义
export const logout = (req, res) => {
res.clearCookie("token", {
sameSite: "none",
secure: true
}).status(200).json("User has been logged out.")
};
此外,上面的代码没有从浏览器中清除cookie,我们将感谢所有帮助
import express from "express";
import postRoutes from "./routes/posts.js";
import authRoutes from "./routes/auth.js";
import usersRoutes from "./routes/users.js";
import cors from "cors";
import cookieParser from "cookie-parser";
const app = express();
app.use(cookieParser());
app.use(
cors({
origin: "http://127.0.0.1:5173", // Replace this with the URL of your frontend
credentials: true, // Allow credentials (cookies) to be sent by the frontend
})
);
app.use(express.json());
app.use("/api/posts", postRoutes);
app.use("/api/auth", authRoutes);
app.use("/api/users", usersRoutes);
app.listen(5175, () => {
console.log("Connected to Backend");
});