【问题标题】:Calling users from angular to node (MEAN) is sending only email and _id to angular从角度调用用户到节点(MEAN)只发送电子邮件和_id到角度
【发布时间】:2019-06-10 00:10:37
【问题描述】:

我正在使用以下代码..

// Node.js
router.get('/users/all', authenticate, (req, res) => {
    User.find({some query}).select('firstName lastName email').then((users) => {
        res.send(users);
    });


//Angular Service
let opts = { headers: this.getCommonHeaders(), params: new HttpParams() };
return this.http.get(getUserDataUrl, opts)
      .pipe(
        map(response => {
          // here is the problem
          console.log(response.json());
          return response.json()
        }),
        catchError(this.handleErrors)
      );

在 opts 标头中我提到了数据类型:

  getCommonHeaders() {
    return new HttpHeaders({
      'Content-Type':  'application/json',
      'x-auth': this.getToken()
    })
  }

在 console.log(response.json()) 中,我在数组对象中只收到电子邮件和 _id。在 res.send(user) 之前在 node.js 上添加相同的 console.log(user) 会显示包含 firstName 和 lastName 的整个数据

然后我将 .lean() 添加到 User 函数中。这允许其余的名字和姓氏出现。如何在不将它们转换为普通对象的情况下获取整个数据?

【问题讨论】:

    标签: node.js angular express mongoose mean


    【解决方案1】:

    对我来说,这似乎是问题所在。当您在猫鼬中使用 find() 方法时,它会给出一个数组。所以你将该数组转换为 json 并使用 res.send() 发送。因此,当您使用 Angular 访问它时。它可能会崩溃并且没有提供正确的格式,因此请尝试像这样更改节点 js 中的代码。 而不是 find() 尝试像这样在猫鼬中使用 findOne() 。我假设您只打算从该查询中获取一个用户,对吗?

    // Node.js
    router.get('/users/all', authenticate, (req, res) => {
    User.findOne({some query}).select('firstName lastName email').then((user) => {
        res.send(user); // there was a typo I changed it too. look in the question not user it was users.
    });
    

    【讨论】:

    • 奇怪地使用 findOne 也给了我同样的结果。甚至将 .send() 更改为 .json() ...
    【解决方案2】:

    尝试使用 res.json("JSON Object");而不是 res.send()..

    其他尝试使用 robomongo 之类的工具检查数据库

    【讨论】:

    • 他说他首先尝试了你答案的第一部分,它提供了包含所有必需细节的完整 json..
    • 我只是尝试了 res.json(users) 而不是 res.send(users) .. 我确实使用 robomongo 来检查数据库。 NodeJS 中的 console.log 给出了完整的结果,包括 firstName、lastName、email、_id ……但是发送到前端后,大部分结果都丢失了。
    • 如果您尝试传递您制作的对象。而不是来自 mongodb 是否可以通过?像 { firstName: "this is test string", lastName: "Last name test", email:"1234abc@gmail.com" }
    • 是的。正如我所说...如果我将它转换为 .lean() 在 mongodb 中,它可以工作。此外,如果我将 mongodb 结果对象的每个元素从其数组中转换,将其转换为 .toObject 并将其附加到另一个空数组中......假设“结果”......并将其发送到前端,它可以工作。跨度>
    猜你喜欢
    • 1970-01-01
    • 2019-09-07
    • 2021-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-25
    • 2018-03-24
    • 2016-05-19
    相关资源
    最近更新 更多