在node.js中,我们需要分析一下URL:
我们需要查看一下http请求,从中提取出请求的URL以及GET/POST参数。
我们需要的所有数据都会包含在request对象中,该对象作为onRequest()回调函数的第一个参数传递。但是为了解析这些数据,我们需要额外的Node.JS模块,它们分别是url和querystring模块。
url.parse(string).query | url.parse(string).pathname | | | | | ------ ------------------- http://localhost:8888/start?foo=bar&hello=world --- ----- | | | | querystring(string)["foo"] | | querystring(string)["hello"]
好了,我们写服务端的代码,即server.js
var http = require("http"); var url = require("url"); function start(route){ function onRequest(request,response){ var pathname = url.parse(request.url).pathname; console.log("Request for " + pathname + " received.") ; route(pathname); response.writeHead(200,{"Content-Type":"text/plain"}); response.write("Hello World"); response.end(); } http.createServer(onRequest).listen(8080); console.log("Server has started."); } exports.start = start;
然后是路由代码:
function route(pathname){ console.log("About to route a request for " + pathname); } exports.route = route;
然后是主类代码:
var server = require("./server"); var router = require("./router"); server.start(router.route);
运行结果:
Administrator@WIN-23C1Q4GKQ4G ~
$ node /example/index.js
Server has started.
Request for /syc received.
About to route a request for /syc