0

I am new to Node.js. I have written simple Node.js program to print hello world. and it works fine.

Now when I passes the querystring along with that then it gives an error

Node.js

var http = require("http");

http.createServer(function (request, response) {

   // Send the HTTP header 
   // HTTP Status: 200 : OK
   // Content Type: text/plain
   response.writeHead(200, {'Content-Type': 'text/plain'});

   // Send the response body as "Hello World"
   response.end('Hello World\n'+request.q);
}).listen(8081);

// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');

Query from Browser

http://127.0.0.1:8081/?q=MrX

It Gives

Hello World
undefined
Mr x
  • 828
  • 1
  • 8
  • 25
  • http://stackoverflow.com/questions/6912584/how-to-get-get-query-string-variables-in-express-js-on-node-js?rq=1 – Pogrindis Mar 09 '16 at 11:35

1 Answers1

1

This may help you

    var http = require("http");
    url = require("url"); 
http.createServer(function (request, response) {

   // Send the HTTP header 
   // HTTP Status: 200 : OK
   // Content Type: text/plain
   response.writeHead(200, {'Content-Type': 'text/plain'});

   // Send the response body as "Hello World"
    var _get = url.parse(request.url, true).query; 
    response.end('Here is your data: ' + _get['data']); 
//   response.end('Hello World\n');
}).listen(8081);

// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');

URL

http://127.0.0.1:8081/?data=MrX
NIket
  • 914
  • 1
  • 6
  • 19