使用节点js从url中获取变量

时间:2015-04-02 15:21:01

标签: javascript node.js url request

我在node.js中编写了一个包含4个模块的简单Web服务器: 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;

我现在要做的是在我的请求网址中传递一些变量:some.url.com:8000/id=1d2d3d4d?num=123?foo=bar

这样我就可以将变量的值放入我的代码中并继续使用它们。

是否有一些更简单的方法,而不仅仅是采用整个路径名并对?分隔符或id,num,foo标记进行分析?

1 个答案:

答案 0 :(得分:0)

您可以使用url.parse - from the node docs