当我在使用身份验证中间件时尝试POST
时,收到错误在将 header 发送到客户端后无法设置 header
。我进行了研究,发现我正在向客户发送数据,而我并不认为是这样。但我无法弄清楚这是在哪里发生的。我认为它在实际的中间件代码中,因为当我在没有中间件的情况下运行代码时,它可以完美地工作。
请原谅我打字不好。这是一项正在进行的工作。我仍在计算我将收到哪些元素。
路线
app.post("/users/post-item",authenticate, itemController.postItem);
身份验证中间件
export const authenticate = async (
req: Request,
res: Response,
next: NextFunction
) => {
const token: any = req.headers["token"];
if (!token) {
console.log("No token");
return res.status(400).send({ message: "Token is not provided" });
}
try {
const decoded: any = await jwt.verify(token, "abc123");
const user = await db("user").where({ id: decoded.id.id });
req.body.user = { user };
next();
} catch (error) {
return res.status(400).send(error);
}
next();
};
Controller
export const postItem = (req: Request, res: Response) => {
const { itemName, price, description, user, location, species } = req.body;
try {
items
.postItem({
itemName: itemName,
price: price,
description: description,
userId: user.user[0].id,
location: location,
species: species
})
.then((data: any) => {
// Header is sent somewhere before here
res.sendStatus(200);
});
} catch (error) {
throw new Error(`Something went wrong: ${error}`);
}
};
PostItem函数
export const postItem = ({
itemName,
price,
description,
userId,
location,
species
}: {
itemName: string;
price: string;
description: string;
userId: string;
location: string;
species: string;
}): any => {
return db("item_for_sale").insert({
name: itemName,
price,
description,
user_id: userId,
location,
species
});
};```
最佳答案
您也在 try..catch
之后调用 next()
。因此 next
函数被调用两次。
try {
const decoded: any = await jwt.verify(token, "abc123");
const user = await db("user").where({ id: decoded.id.id });
req.body.user = { user };
next();
} catch (error) {
return res.status(400).send(error);
}
next();//<<<<====this next
关于javascript - “发送到客户端后无法设置 header ” - 我正在设置 header ,但找不到位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56935195/