@breakerthb
2016-07-11T06:38:29.000000Z
字数 1723
阅读 1300
NodeJS
在NodeJS接收到Client端发来的GET/POST请求时,我们需要先分析URL得到相关内容,之后进行相应的处理。
我们需要的所有数据都会包含在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() {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received.");
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}
http.createServer(onRequest).listen(8000);
console.log("Server has started.");
}
exports.start = start;
这段代码中通过url.parse(request.url).pathname获取到了URL的内容。
路由功能是为了在得到请求后可以先通过路由模块进行功能分流。也就是说,通过路由模块,可以实现来自/start和/update的请求使用不同代码来处理。
路由模块router.js:
// router.js
function route(pathname) {
console.log("About to route a request for " + pathname);
}
exports.route = route;
目前,这个模块没有任何实际的功能。
接下来需要在server.js中引入路由模块。
// 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(8888);
console.log("Server has started.");
}
exports.start = start;
此处修改了start函数,在启动是需要把路由模块传入。
在index.js中,我们加入下面的代码:
var server = require("./server");
var router = require("./router");
server.start(router.route);
此时,我们可以直接执行下面的句子启动服务器:
node index.js
这时从浏览器输入:http://localhost/start?foo=bar&hello=world
此时在服务器端出现: