0

Just out of curiosity I started to play with Node.js, I create a simple server with this code:

var http = require("http");

http.createServer(function(request, response) {
......
}).listen(8888);

Inside the createServer function I have a simple string that I want to return to another app.

The workflow is:

  • Other app send name and lastName
  • Node.js app recieve this data
  • Build the a JSON string with that data
  • Retrieve the JSON string to the other app

Currently I'm hardcoding the name and lastName and building the JSON string with them, but I have all that code on the createServer function, but the problem is that the createServer function is called only on the server startup.

How can I receive and send data from a Node.js app to another app?

2
  • I'm a little confused. Are you asking how to receive requests and send responses? Commented Aug 20, 2014 at 17:26
  • Hi Chris, yes, i.e. I have this URL http://localhost:8888/app?name=foo&lastName=bar and I want get the name and lastName from the request and create a JSON using that parameters and finally return the JSON Commented Aug 20, 2014 at 20:16

1 Answer 1

2

When you call http.createServer(), the parameter you pass is actually the function to handle new requests. This function will be called for each and every request. It doesn't run immediately.

Just make the HTTP request from your other application and you will see your function being called.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Brad, for example, I'm trying with this URL http://localhost:8888/app/id=3, and inside the createServer I have this line: console.log(JSON.stringify(request.query)); but it prints undefined and if I try with the specific parameter name: console.log(JSON.stringify(request.query.id)); I get an error about the id not being defined
@cesar_k13 Why would you expect anything else? query isn't a property of the IncomingMessage object passed to your request handler. It sounds like you read some Express documentation. If you want to use Express, you need to use Express. Otherwise, there are examples in the documentation for how to access and parse the query string: nodejs.org/api/http.html#http_message_url

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.