Tecnico
Tecnico

Reputation: 459

.json in Ionic 2

Im working in one application in Ionic 2 and I'm connecting it with node.js server. For send data (server - Ionic) I send like this:

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

In Ionic, I get the data like this:

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

Where resp is 0 or 1 so... in this example work fine.

My problem is when I need to send more data in my server so... if in "res.end(data)" data is the string "1_2_3"

In Ionic, I get this error:

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

Somebody know how can I solve it?

Upvotes: 0

Views: 597

Answers (1)

sebaferreras
sebaferreras

Reputation: 44669

Try with something like this in your server:

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

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

And then in Ionic code:

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
...

Upvotes: 1

Related Questions