簡體   English   中英

res.send() 發送 null object

[英]res.send() sending null object

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. 我正在使用 cors 將數據從 localhost/8081 的快速后端發送到 localhost/4200 的 angular 前端。

快遞后台

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

服務.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
}

console.log(req.body) 返回 {_id: 'someid'},console.log(docs) 返回整個人 object 找到的 id 和 console.log(result) 顯示與 console.log(文檔)

angular前端

人員詳細信息組件

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

Angular 前端錯誤

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) 沒有得到人 object 所以人總是 null object。 如何修復它,以便 person => this.person = person 使 this.person 成為使用 res.send() 發回的人 object?

您不會在服務 function 中等待回調 function。

將其包裝在 promise 中,或使用相應的 promise 作為findById

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

編輯mongoose 內置了 promise 支持

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM