-1
我寫了一個簡單的web服務器包含4個模塊的node.js得到變量從網址: index.js, server.js, requestHandler.js router.js
使用節點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;
我想現在要做的就是通過我像請求URL中的一些變量是什麼即:some.url.com:8000/id=1d2d3d4d?num=123?foo=bar
這樣我就可以將變量的值存入我的代碼並繼續使用它們。
是否有一些更簡單的方法,而不僅僅是取整個路徑名並分析?
分隔符或id,num,foo
標籤?
檢查這個問題:http://stackoverflow.com/questions/6912584/how-to-get-get-query-string-variables-in-node-js – 2015-04-02 15:24:47
需要注意的是,在「require」調用結束時不需要有「.js」。這是暗示的。 – tadman 2015-04-02 18:11:29