【发布时间】:2021-09-09 10:52:27
【问题描述】:
我的目标是
如果找到任何数据 findOne() 函数使用内容更新当前端点,如果没有使用 Schema 创建新元素。
问题
如果 db 中没有数据,那么首先if 它会将ERR_HTTP_HEADERS_SENT 与console.log = 1 相结合,但如果有,则使用console.log = 3 一切正常。
try {
const find = await endPointSchema.findOne({ uuid: uuid });
if (!find) {
const data = new endPointSchema({
uuid: uuid,
endpoint: [{ point: Endpoint, Content }],
date: Date.now(),
});
await data.save();
console.log(1);
res.status(200).json({ message: "Succesfully Created new Breakpoint" });
return;
} else {
if (!find.endpoint) {
console.log(2);
res.end();
return;
} else {
console.log(3);
res.end();
return;
}
}
} catch (e) {
console.log(e);
res.end();
return;
}
我的端点
route.post("/endpoint", AuthorizePanel, async (req, res) => {
const { role, username, uuid } = req.user;
if (!role && !username && !uuid) {
res.sendStatus(401);
return;
}
const { Endpoint, Content } = req.body;
if (Endpoint === username) {
res.status(403).json({ message: "Endpoint can not be same with your username!" });
return;
}
try {
const find = await endPointSchema.findOne({ uuid: uuid });
if (!find) {
const data = new endPointSchema({
uuid: uuid,
endpoint: [{ point: Endpoint, Content }],
date: Date.now(),
});
await data.save();
console.log(1);
res.status(200).json({ message: "Succesfully Created new Breakpoint" });
return;
} else {
if (!find.endpoint) {
console.log(2);
res.end();
return;
} else {
console.log(3);
res.end();
return;
}
}
} catch (e) {
console.log(e);
res.end();
return;
}
});
授权面板
import jwt from "jsonwebtoken";
export const AuthorizePanel = (req, res, next) => {
const authHeader = req.headers.authorization;
if (authHeader) {
const token = authHeader.split(" ")[1];
jwt.verify(token, process.env.JWT_SECRET, (err, user) => {
if (err) {
res.sendStatus(403)
return
}
req.user = user;
next();
});
}
next();
};
【问题讨论】:
-
1 在不成功的流程中打印?数据是否保存?
-
是的,我知道这很有趣,但是在 http 标头错误之后我看到它已保存。
-
该错误通常是当您在发送一个响应后发送 res 时。查看您的代码,我不明白这是怎么回事。您可以在使用 res 的地方添加/检查更多代码流吗?
-
就像我无法理解的那样
-
可能在此函数之前的某个地方还有另一个 res.end() 或 res.send()。
标签: javascript node.js express mongoose nosql