Mr x
Mr x

Reputation: 868

how to access query string with Node.js

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

Upvotes: 0

Views: 113

Answers (1)

NIket
NIket

Reputation: 924

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

Upvotes: 1

Related Questions