Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send parameters to Node.JS basic server

Tags:

node.js

I am learning Node.JS and this is the most commonly available example of server by Node.JS

// Load the http module to create an http server.
var http = require('http');

// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
//    var name=request.getParameter('name');
//    console.log(name);
    console.log('res: ' + JSON.stringify(response.body));
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.end("Hello World\n");
});
// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);

Now when I am executing this from console it works fine, and from browser also it works fine, by hitting the URL: localhost:8000

But now I also want to send some parameters to this server, so I tried localhost:8000/?name=John and few more URL's but none of them work, Can anyone help me?

Thanks in advance!!

like image 361
Nick Div Avatar asked Feb 14 '23 12:02

Nick Div


2 Answers

try:

var url = require('url');
var name = url.parse(request.url, true).query['name'];
like image 122
Nick Rempel Avatar answered Feb 16 '23 12:02

Nick Rempel


Node's HTTP API is rather low-level compared to other frameworks/environments that you might be familiar with, so pleasantries like a getParameter() method don't exist out of the box.

You can get the query-string from the request's url, which you can then parse:

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

var server = http.createServer(function (request, response) {
    var parsedUrl = url.parse(request.url, true);
    var query = parsedUrl.query;

    console.log(query.name);

    // ...
});
like image 36
Jonathan Lonowski Avatar answered Feb 16 '23 11:02

Jonathan Lonowski