Syed Daniyal Asif Syed Daniyal Asif - 17 days ago 5
Node.js Question

How to get GET (query string) variables in HTTP on Node.js?

How can i get the variables from query string in Node.js just like we get them in $_GET/$_POST in PHP?

Here is my code, I have passed parameters through XMLHttpRequest. but i dont know how to get parameters. Please give me any suitable solution. I want to insert values in database.

server.js

var http = require('http'),
fs = require('fs'),
url = require('url');

var db = require('../db');

http.createServer(function(request, response){

var url = require('url');
var url_parts = url.parse(request.url, true);
var query = url_parts.query;

console.log('Name: ' + query.name);

}).listen(8001);


index.hjs

function calling()
{

xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET","http://localhost:8001/name=user_name&cell=01234-1234567", true);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
string=xmlhttp.responseText;
}
}
xmlhttp.send();
}


output

Name: undefined

Answer

Looks like you request wrong URL. Should be

http://localhost:8001/?name=user_name&cell=01234-1234567

instead of

http://localhost:8001/name=user_name&cell=01234-1234567

so name goes in query.

Comments