Reputation: 133
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 });
}
}
Upvotes: 0
Views: 2285
Reputation: 3720
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());
}
);
Upvotes: 5
Reputation: 133
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();
}
Upvotes: 0