简体   繁体   English

如何使用 HTTP 发送反对意见 在 Angular 中发布

[英]How to send an objecto using HTTP Post in Angular

Im trying to send an object called Pack to my API Rest server from my angular service.我试图从我的 ZD18B8624A0F5F721DADD7B823 服务发送一个名为 Pack 的 object 到我的 API Rest 服务器。 In order to do so, I have the following function:为此,我有以下 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.但是,我知道我尝试发送 Pack 的方式不正确。 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.我想知道如何正确发送 Pack,以便可以在我的 API Rest 中获取它,然后如何访问 object 接收。 I know that when you use GET, you can do:我知道当你使用 GET 时,你可以这样做:

const Pack = req.query.Pack;

How can I do the same with POST?我怎样才能对 POST 做同样的事情?

My API Rest POST calling is:我的 API Rest POST 调用是:

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;

})

I would suggest is to use Observable insteaf of Promise:我建议使用 Promise 的 Observable insteaf:

      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 )我建议你实现一个干净的代码:(总是给你的数据一个类型而不是类型 any )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM