res.send() sending null object

Viewed 1425

I am trying to send back a person object with res.send() from the express backend to the angular frontend but res.send() is always sending a null object. I am sending data from express backend at localhost/8081 to angular frontend at localhost/4200 with cors.

express backend

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;
      });
    };

output

{ _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
}

The console.log(req.body) returns {_id: 'someid'} and the console.log(docs) returns the entire person object found with the id and console.log(result) displays the same thing as console.log(docs)

angular frontend

person-detail.component

  @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
  }

person.service

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

Angular front end errors

core.js:4081 ERROR Error: NodeInjector: NOT_FOUND [NgControl]
at getOrCreateInjectable (core.js:3819)
at Module.ɵɵdirectiveInject (core.js:13733)
at NodeInjectorFactory.NgControlStatus_Factory [as factory] (forms.js:677)
at getNodeInjectable (core.js:3913)
at instantiateAllDirectives (core.js:7973)
at createDirectivesInstances (core.js:7356)
at Module.ɵɵelementStart (core.js:13882)
at PersonDetailComponent_div_0_Template (person-detail.component.html:6)
at executeTemplate (core.js:7329)
at renderView (core.js:7138)

personService.getPerson(id) isn't getting the person object so person is always a null object. How can I fix it so that person => this.person = person makes this.person the person object that was sent back with res.send()?

1 Answers

You're not waiting for the callback function in your service function.

Wrap it inside a promise or use the corresponding promise for findById.

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

Edit there's a built in promise support by mongoose.

Related