Fane Fane - 4 months ago 23
Node.js Question

How to return value from node to origin (angular2 request)

I have code in my nodejs instance that receives a post request (successfully) and also shows arguments sent via json (I'm requiring body-parser in the server side). As soon as the post requests is received I immediately perform

return "testing";
to check on whether the value is being returned successfully. However, my angular2 callback (done as shown) does not fire or display any logs. Any idea on why?

var to_send = JSON.stringify({"test": argument});

var headers = new Headers();
headers.append('Content-Type', 'application/json');

this.http
.post('http://localhost:8080/',
to_send, {
headers: headers
})
.map((res) => res.json() )
.subscribe(
(response) => { console.log("Success Response" + response)},
(error) => { console.log("Error happened" + error)},
() => { this.parseResponse(res); }
);


The function parseResponse simply console.logs("something returned");

EDIT:



Here is how my code is now, still failing (no log inside parseResponse is triggered):

var to_send = JSON.stringify({"test": argument});

var headers = new Headers();
headers.append('Content-Type', 'application/json');

this.http
.post('http://localhost:8080/',
to_send, {
headers: headers
})
.map((res) => res.json() )
.subscribe(
(response) => { console.log("Success Response",response)},
(error) => { console.log("Error happened",error)},
() => { this.parseResponse(res); }
);


And in my server I am returning the following:

var to_return = {};

to_return["message"] = "success";

return to_return;


Still, it does not work at all. Any idea on why?
parseResponse
is a simple log "feedback received"...

Answer

You do

this.http...
  .map((res) => res.json() )

By this you convert response to json, since it's not json, it fails. You can use method text() instead to get string:

.map((res) => res.text())

Or you can return an object from back-end:

return {result: "testing"}

and read field result inside subscribe

Update:

You can output the res in map method to see what it really contains:

.map((res) => {
  console.log(res);
  return res.json();
})

One more thing: call this.parseResponse(res); res doesn't exist in this scope. It will be undefined inside parseResponse