Home > OS >  Unable to post HTTP request from angular to node js localhost server
Unable to post HTTP request from angular to node js localhost server

Time:11-09

I have an express node js server, which listens to localhost at port 3000, and prints the JSON content. If I use postman, it prints the JSON properly.

var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json())

var port = 3000;

app.post('/instance', function(req, res) {
    const obj = JSON.parse(JSON.stringify(req.body))
    console.log(obj);
    //res.send(req.body);
});


// start the server
app.listen(port);
console.log('Server started! At http://localhost:'   port);

In angular html, i have an ngFor that sends a list item when a button is clicked.

<ng-container *ngFor="let instance of instancesList">
    <tr  style="color:#111111">
      <td>{{instance.id}}</td>
      <td>{{instance.name}}</td>
      <td>{{instance.zone}}</td>
      <td>{{instance.ip}}</td>
      <td> <button (click)="onClick(instance)" type="button" >test</button></td>
    </ng-container>

At this point, when the button is clicked, I want a JSON with the item data to be sent to the server, and just be printed. It does not happen, the server doesn't print the json content, but it prints the content if sent from postman.

i've been strugling for a few days now, I appreciate any help.


const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type':  'application/json',
  })
};

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})

@Injectable({providedIn:'root'})
export class AppComponent{
  instancesList = instances;
  baseUrl = "http://localhost:3000/instance"

  constructor(private http: HttpClient) { } 

  onClick(instance: Instance) : Observable<Instance>{
    const json = JSON.stringify(instance)

    return this.http.post<Instance>(this.baseUrl, json, httpOptions)

    // prints the json on the webpage just for testing
    alert(JSON.stringify(instance));       
}
}

I tried searching stackoverflow and try different methods, none helped.

CodePudding user response:

you didn't subscribe to the Observable returned from the the HTTP request. simply instead of return it - do that:

this.http.post<Instance>(this.baseUrl, json, httpOptions).subscribe(data => 
 { 
   // here you can do something with the data that returned
 })

CodePudding user response:

So just in case, somebody finds this in the future, the issue was related to something else

CORS error due to browser's same origin policy. To get around this, you need to tell your browser to enable your client and your server to share resources while being of different origins. In other words, you need to enable cross-origin resource sharing or CORS in your application.

The solution is to add a proxy config as stated in the official angular documentation. https://angular.io/guide/build#proxying-to-a-backend-server

  • Related