-1

Im trying to send an object called Pack to my API Rest server from my angular service. In order to do so, I have the following function:

save_pack(Pack: any){
    return new Promise((resolve, reject) =>{
      this.http
        .post("http://localhost:8000/save_pack",Pack)
        .subscribe(res => {
            resolve(res);
          },
          (err: any) => {
            reject(err);
          }
        )
    });
  }
}

However, I know that the way im trying to send Pack is not correct. I would like to know how can I send Pack correctly so I can get it in my API Rest and then how can I access that object receive. I know that when you use GET, you can do:

const Pack = req.query.Pack;

How can I do the same with POST?

My API Rest POST calling is:

app.post('/save_pack', async (req,res) => {
    console.log(req.body)
    const Pack = req.body.Pack;
    console.log("Paquete: " + Pack);

    let result = await save_pack(Pack);
    res.send(result)
    return res;

})

1 Answers1

0

I would suggest is to use Observable insteaf of Promise :

      save_pack(pack: any){
            this.httpClient.post<any>('http://localhost:8000/save_pack', pack)
 .subscribe(result => {
  console.log('result saved with success');
   }, err => {
  console.log('err saving new pack', pack);
    
   });
              
          }
        }

For the back-end, you can get the body data :

const pack = req.body.pack;

My suggestion for you to implement a clean code : (always give a type for your data instead of type any )

Rebai Ahmed
  • 1,509
  • 1
  • 14
  • 21