【问题标题】:how to send data from angular to node.js如何将数据从角度发送到node.js
【发布时间】:2020-09-17 06:14:15
【问题描述】:

我需要将一些数据从 angular 传递到 node.js 服务器。这是我的角度后列表组件: 从'@angular/core'导入{组件,OnInit}; 从“@angular/common/http”导入 { HttpClient };

@Component({
  selector: 'app-postlist',
  templateUrl: './postlist.component.html',
  styleUrls: ['./postlist.component.css']
})
export class PostlistComponent implements OnInit {

  constructor(private http: HttpClient) { }
  public data="test";
  ngOnInit(): void {
      this.http
        .post("http://localhost:3000/api/book",this.data);  
  }

}

我的 node.js 服务器:

const express=require('express');
var app = express();
app.post('/api/book', function(req, res, next){
    var data = req.body.params;
    console.log(data);
 });
 app.listen(3000);

我正在尝试控制台记录数据,但没有任何反应。

【问题讨论】:

  • 查看previous post,了解如何在 node.js 中获取 POST 正文

标签: node.js angular angular-fullstack


【解决方案1】:

您在通话中缺少 .subscribe。将您的代码更改为:-

  ngOnInit(): void {
      this.http
        .post("http://localhost:3000/api/book",this.data).subscribe();  
  }

在 nodejs 中只打印 req.body

【讨论】:

    【解决方案2】:

    如果您计划打印有效载荷 this.data,请使用 req.body 而不是 req.body.params。 还要检查控制台中是否有任何cors 错误,这也可能会阻止您的数据到达您的网络服务器。

    【讨论】:

      【解决方案3】:

      在服务器中,您必须像这样将消息的格式更改为 JSON

      app.get('/api/GetFlux',function(req,resp){
        let data = "hello"
        resp.send(JSON.stringify(data));
      })
      
      

      在角度层面

      GetFlux():Observable<any[]>{
        return this.http.get<any>(this.APIUrlNode+'/GetFlux');
      }
      
      
      
      
            this.service.GetFlux().subscribe(res =>{
              this.fluxList = {
                data:res
              } 
              console.log("Data from node "+this.fluxList.data)
                   //,
            }, err => {
              console.log(" err = "+err)
            })
      
      
      
      
      
      
      

      【讨论】:

        猜你喜欢
        • 2017-02-04
        • 2019-03-11
        • 2018-03-24
        • 2019-04-29
        • 1970-01-01
        • 2017-09-07
        • 2021-08-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多