2016-07-23 112 views
0

我有服務器的NodeJS聽&等待POST請求http://localhost:3000/api/updateLocation 服務器與郵差爲JSON POST請求測試,所有的工作,輸出的NodeJS「得到數據」來安慰。但Angular2似乎並沒有將數據發送到服務器。 Screenshot PostMan角2服務HTTP POST不起作用

最新問題?

的NodeJS server.js:

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

離子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 }); 
    } 
} 

回答

5

您需要訂閱HTTP動作,否則該請求ISN」實際上被解僱了。它在使用前一直保持「冷」狀態。

這會工作,如果你的API是返回一個JSON響應,例如:

this.http.post(this.url, body, { headers }).subscribe(
     data => { 
      console.log(data.json());   
     } 
); 
+0

是這個數據變量是從服務器的JSON-ED迴應?所以如果節點應答爲res.json({a:b}),那麼data = {a:b}?不過,正如你所看到的,我沒有參數就訂閱了,所以我們都假設我們的答案都是正確的。 –

+0

是的,'數據'包含響應。它實際上是@ angular/http模塊的Response對象。 'data'變量當然可以是任何你喜歡的東西。 – Delosdos

0

問題所解決:

1)導入Rxjs/Rx

2)改變標頭進行了urlencoded

3)修飾功能sendLocation此(添加訂閱()方法):

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