2016-07-23 98 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(); 
    }