0

I have nodejs server listening & waiting for post requests http://localhost:3000/api/updateLocation Server is tested with PostMan for JSON post request and all is working, nodejs outputs 'Got data' to console. But Angular2 doesnt seems to send data to server.Screenshot PostMan

Whats the problem?

NodeJS server.js:

api.post('/updateLocation', function(req, res){
  //res.send(req.body);
  console.log('Got data');
});

Ionic 2 home.ts:

import {Component} from '@angular/core';
import {NavController} from 'ionic-angular';
import {Service} from '../../service';

@Component({
  templateUrl: 'build/pages/home/home.html',
  providers: [Service]
})
export class HomePage {
  constructor(private navCtrl: NavController, service: Service) {
    setInterval( ()=> {
      service.sendLocation({ x: '46.303344', y: '28.655268' });
    }, 1000);
  }

}

service.ts:

import {Injectable} from '@angular/core';
import {Http, Headers} from '@angular/http';

@Injectable()
export class Service {
  http : any;
  url : string = 'http://localhost:3000/api/updateLocation';
  constructor(http: Http){
    this.http = http;
  }

  sendLocation(location){
    let body = JSON.stringify(location);
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    return this.http.post(this.url, body, { headers });
  }
}

2 Answers 2

5

You need to subscribe to the http action, otherwise the request isn't actually fired. It remains 'cold' until it's used.

This would work, if your api was returning a json response, for example:

this.http.post(this.url, body, { headers }).subscribe(
        data => {
            console.log(data.json());           
        }
);
Sign up to request clarification or add additional context in comments.

2 Comments

is this data variable is JSON-ed response from server? so if node answer to requiest as res.json({a:b}), then data = {a:b} ? However as you can see I subscribed without arguments, so both our answers I assume are right.
Yes, 'data' contains the response. It's actually a Response object from the @angular/http module. The 'data' variable can be anything you like of course.
0

Problem solved by:

1) importing Rxjs/Rx

2) Changing headers to urlencoded

3) modifying function sendLocation to this (added subscribe() method):

  sendLocation(location){
    let body = JSON.stringify(location);
    let headers = new Headers();
    headers.append('Content-Type', 'application/x-www-form-urlencoded');
    this.http.post(this.url, body, {headers: headers}).subscribe();
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.