.json 在离子 2 中

.json in Ionic 2

我在 Ionic 2 中的一个应用程序中工作,我正在将它与 node.js 服务器连接。 对于发送数据(服务器 - Ionic),我这样发送:

http.createServer(function (req, res){
...
res.end(data);  // data is 0 or 1
}

在 Ionic 中,我得到这样的数据:

this.http.post("http://192.168.1.100:8080/post", 'PidoDatosClima' + '_' + this.parameter1)
            .subscribe(data => {
                resp=data.json()
                console.log(resp);
...

其中 resp 是 0 或 1 所以...在这个例子中工作正常。

我的问题是当我需要在我的服务器中发送更多数据时...如果 "res.end(data)" 中的数据是字符串“1_2_3”

在 Ionic 中,我收到此错误:

EXCEPTION: SyntaxError: Unexpected token _ in JSON at position 1

有人知道我该如何解决吗?

在你的服务器中尝试这样的东西:

var data = { "value" : "1_2_3" };

res.end(JSON.stringify(data));  // Now data is an object with the 1_2_3 value

然后在 Ionic 代码中:

this.http.post("http://192.168.1.100:8080/post", 'PidoDatosClima' + '_' + this.parameter1)
         .map(res => res.json())
         .subscribe(data => {
                console.log(data.value);   // Access the value property
...