-1

i need to pass some data from angular to node.js server. this is my angular postlist component: import { Component, OnInit } from '@angular/core'; import { HttpClient } from "@angular/common/http";

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

}

my node.js server:

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

i'm trying to console.log the data but nothing happens.

Igli
  • 7
  • 4
  • Check out this [previous post](https://stackoverflow.com/questions/11625519/how-to-access-the-request-body-when-posting-using-node-js-and-express/49943829) on how to get the body of a POST in node.js – Mark S. May 29 '20 at 16:02

3 Answers3

1

you are missing .subscribe in your call. Change your code to :-

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

and in nodejs just print req.body

Aakash Garg
  • 8,402
  • 2
  • 5
  • 19
0

If you are planning on printing the payload this.data, take req.body instead of req.body.params. And also check if you have any cors errors in console, that can also be blocking your data from reaching your web server.

0

in the server, you must change the format of your message to JSON like this

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

at angular level

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






Marouane
  • 3
  • 2