提问者:小点点

res.send()发送空对象


我试图将一个带有res.send()的person对象从express后端发送回angular前端,但是res.send()总是发送一个null对象。 我正在用CORS将数据从localhost/8081的express后端发送到localhost/4200的angular前端。

express后端

Controller.js

controller.getPerson = async (req, res) => {
   try{
      console.log(req.body);
      var result = await service.getPerson(req.body._id));
      console.log(result);
      res.send(result); <--- sending undefined object or nothing at all instead of result
   } 
   catch(error)
   {
        console.log("controller/get_person)", error)
   }
};

service.js

service.getPerson = (data) =>{;
       return Person.findById({'_id':data}, function(err, docs){
        console.log(docs);
            return docs;
      });
    };

输出量

{ _id: '5f126357aea7624680d07ee2' } <-- console.log(req.body)
console.log(docs)
{
  _id: 5f126357aea7624680d07ee2,
  first_name: 'qwer',
  last_name: 'qwer',
  __v: 0
}
console.log(result)
{
  _id: 5f126357aea7624680d07ee2,
  first_name: 'qwer',
  last_name: 'qwer',
  __v: 0
}

console.log(req.body)返回{_id:'someid'},console.log(docs)返回使用id找到的整个person对象,console.log(result)显示与console.log(docs)相同的内容

角锋

人员-详细信息。组件

  @Input() person: Person;
  getPerson(): void {
    const id = this.route.snapshot.paramMap.get('id');
    this.personService.getPerson(id)
    .subscribe(person => this.person = person); <-- this.person is not set because person is undefined or doesn't exist
  }

个人服务

  public getPerson(_id){
        return this.http.post<Person>('http://localhost:8081/get_person', {_id});
  }

PersonService.getPerson(id)没有获取person对象,因此person始终是空对象。 我怎样才能修复它,使人=>; this.person=person使this.person成为与res.send()一起发送回的person对象?


共1个答案

匿名用户

您没有在服务函数中等待回调函数。

将其包装在promise中,或者对FindById使用相应的promise。

service.getPerson = (data) => {
       return new Promise(resolve => { 
           Person.findById({'_id':data}, function(err, docs){
             console.log(docs);
             resolve(docs);
           });
       });
};

编辑有一个内置的承诺支持猫鼬。