0

I have written a simple web server in node.js containing 4 modules: index.js, server.js, requestHandler.js router.js

//index.js:
var server = require('./server.js');
var router = require('./router.js');
var requestHandlers = require('./requestHandlers.js');

var handle = {};
handle['/id'] = requestHandlers.getID;

server.start(router.route, handle);


//server.js
var http = require('http')
var url = require('url')

function start(route, handle){
  function onRequest(request, response) {
    var pathname = url.parse(request.url).pathname;
    console.log('Request for ' + pathname + ' received');

    request.setEncoding('utf-8');

    route(handle, pathname, response);
  }

  http.createServer(onRequest).listen(8000);
  console.log("server started");
}

exports.start = start


//requestHandlers.js
var exec = require('child_process').exec;
var querystring = require('querystring');

function getID(response,pathname) {
  console.log('Request handler start was called.');
  console.log(pathname);
  var body = '<html>'+
  '<head>'+
  '<meta http-equiv="Content-Type" content="text/html; '+
  'charset=UTF-8" />'+
  '</head>'+
  '<body>'+
  '<h1> Hello Dude <\h1>'
  '</body>'+
  '</html>';

  response.writeHead(200, {'Content-Type':'text/html'});
  response.write(body);
  response.end();
}
exports.getID = getID;


//router.js
function route(handle, pathname, response, postdata) {

  console.log('About to route a request for ' + pathname);

  if(typeof handle[pathname] === 'function') {
    return handle[pathname](response, pathname);
  } else {
    console.log('No request handler found for ' + pathname);
    response.writeHead(404, {'Content-Type': 'text/plain'});
    response.write('404 Not Found');
    response.end();
  }
}

exports.route = route;

What I want to do now is passing some variables within my request url like that: some.url.com:8000/id=1d2d3d4d?num=123?foo=bar

So that I can get the values of the variables into my code and go on working with them.

Is there some easier approach than just taking the whole pathname and analysing it for ? separators or the id,num,foo tag?

2
  • Check this question: stackoverflow.com/questions/6912584/… Commented Apr 2, 2015 at 15:24
  • As a note, it's not necessary to have ".js" at the end of your require calls. That's implied. Commented Apr 2, 2015 at 18:11

1 Answer 1

0

You can use url.parse - from the node docs

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.