在 Nodejs中,当接收到请求时,需要一个模块解析这些数据,可以用 url 和 querystring 模块来解析数据,然后通过路由根据这些数据来执行相应的代码。
比如一个简单的server模块:
var http = require("http");
var url = require("url");
function start() {
function onRequest(request, response) {
var routeName = url.parse(request.url).routeName;
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("onRequest");
response.end();
}
http.createServer(onRequest).listen(8888);
console.log("server start.");
}
exports.start = start;
通过url模块解析出路由名称后,便可以根据对应的路由名称处理对应的事件。
定义一个路由模块router.js:
function route1(routeName) {
console.log(`route1:${routeName}`);
}
function route2(routeName) {
console.log(`route2:${routeName}`);
}
exports.route = {
'/r1': route1,
'/r2': route2
};
改造server.js:
var http = require("http");
var url = require("url");
var router = require("./router");
function start() {
function onRequest(request, response) {
var routeName = url.parse(request.url).pathname;
var fun = router.route[`${routeName}`]
if (fun) {
fun(routeName);
}
response.writeHead(200, { "Content-Type": "text/plain" });
response.write("onRequest");
response.end();
}
http.createServer(onRequest).listen(8080);
console.log("server start.");
}
exports.start = start;
启动脚本:
var server = require("./server");
server.start();
当访问 localhost:8080/r1 的时候,VS Code控制台输出: