javascript - “发送到客户端后无法设置 header ” - 我正在设置 header ,但找不到位置

标签 javascript node.js express

当我在使用身份验证中间件时尝试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/

相关文章:

javascript - owl-Carousel 没有停止垂直拖动

javascript - 如何在启动 Node.js 控制台时运行脚本?

node.js - 无法在 Express 路由器内返回请求

javascript - 如何在 Node js 中从远程 git 存储库中提取标签,而无需在应用程序中安装 git?

node.js - Express.js/Node 禁用某些请求日志

json - 转换为 json 时序列化下划线/蛇形大小写

javascript - 将 fullcalendar 与 javascript 一起使用,如何修改参数列表并重新获取?

javascript - 在 JavaScript/jQuery 中拦截自动表单提交事件

javascript - ubuntu 上的 cloud9 在 chrome 中出现 ace.js 404 错误

angularjs - 在html5模式下使用ng-route重新加载 Angular 页面不会返回index.html