【问题标题】:Express/Node.js post endpoint shows [object Object] instead of Array of ObjectsExpress/Node.js 后端点显示 [object Object] 而不是 Array of Objects
【发布时间】:2020-10-10 00:01:57
【问题描述】:

我在前端使用 Angular 并向使用 Express 构建的后端发送发布请求。

这是 Angular 代码的外观:

  addEntry() {
    let type = "Random Type";
    let location = "Random Location";
    let date = new Date();
    let results = [
      { name: "my first name", age: 23 },
      { name: "new second name", age: 35 },
    ];

    return this.http.post<{ message: string }>(
      this._url + "/myendpoint/add",
      { type, location, date, results }
    );
  }

这就是 express 代码的样子:

router.post(
  "/add",
  middleware.verifyToken,
  async function (req, res) {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(422).json(errors.array());
    }

    try {
      let userID = req.tokenData.userID;
      let user = await User.findOne({ _id: userID });
      if (user === null || user.length <= 0) {
        return res.status(422).json("Could not add entry");
      } else {
        let type = req.body.type;
        let location = req.body.location;
        let date = req.body.date;

        console.log(req.body);

        let results = req.body.results.map(async (el) => {
          let result = await Entry.findOne({ name: el.name });
          return {
            name: result.name,
            age: el.age,
          };
        });

        [some more code ...]

      }
    } catch (err) {
      console.log(err);
      return res.status(422).json(err);
    }
  }
);

控制台日志输出:

{
  type: 'Random Type',
  centre: 'Random Location',
  date: '2020-06-19T16:50:25.357Z',
  results: '[object Object]'
}

我也收到了这个错误,可能是因为结果显示为“[object Object]”;

TypeError: req.body.results.map is not a function

如何在 Express 中获取结果数组而不是 '[object Object]'?我在 Express 中启用了以下设置:

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

【问题讨论】:

  • 您是如何尝试对 POST 正文进行字符串化的? JSON.stringify({ type, location, date, results })
  • 感谢您的帮助...它仍然无法自行工作...非常奇怪的行为。我尝试将它与 JSON 解析、encodeURIComponent 和 decodeURIComponent 结合起来,但它似乎可以工作。
  • 您不需要对字符串化的 JSON 进行编码,因为您没有在 URI/URL 中发送它。但是您可能需要将http 请求中的Content-Type 标头设置为application/jsonContent-Type 标头将告诉 Express 如何处理正文中的数据。
  • 我将 content-type 标头设置为 application/json,但 Angular 会转义 JSON.stringify() 并且我在后端收到的是包含大量“
  • 如果你不对 JSON 正文进行字符串化,而是放入 application/json Content-Type 标头,那么请求正文是什么类型(typeof(req.body))?

标签: node.js angular express http


【解决方案1】:

我的声誉较低,所以我无法发表评论,您是否尝试过 results[1]['name']; ?

【讨论】:

  • 应该是这样,results[1]['name'];
  • 我试过......仍然“未定义”。由于某种原因,它无法识别数组,因为 map 函数也不起作用,它说“req.body.results.map 不是函数”。
【解决方案2】:

在 Angular 中:结果:encodeURIComponent(JSON.stringify(results));

在 Express 中:JSON.parse(decodeURIComponent(req.body.results));

【讨论】:

    猜你喜欢
    • 2022-12-01
    • 1970-01-01
    • 2021-07-15
    • 2022-12-01
    • 2012-02-29
    • 2021-05-14
    • 2014-07-28
    • 2021-12-03
    相关资源
    最近更新 更多