下面是一个 REST API Web 服务的示例,它根据发送到服务器的 url 动态加载处理程序 js 文件:
服务器.js
var http = require("http");
var url = require("url");
function start(port, route) {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
console.log("Server:OnRequest() Request for " + pathname + " received.");
route(pathname, request, response);
}
http.createServer(onRequest).listen(port);
console.log("Server:Start() Server has started.");
}
exports.start = start;
路由器.js
function route(pathname, req, res) {
console.log("router:route() About to route a request for " + pathname);
try {
//dynamically load the js file base on the url path
var handler = require("." + pathname);
console.log("router:route() selected handler: " + handler);
//make sure we got a correct instantiation of the module
if (typeof handler["post"] === 'function') {
//route to the right method in the module based on the HTTP action
if(req.method.toLowerCase() == 'get') {
handler["get"](req, res);
} else if (req.method.toLowerCase() == 'post') {
handler["post"](req, res);
} else if (req.method.toLowerCase() == 'put') {
handler["put"](req, res);
} else if (req.method.toLowerCase() == 'delete') {
handler["delete"](req, res);
}
console.log("router:route() routed successfully");
return;
}
} catch(err) {
console.log("router:route() exception instantiating handler: " + err);
}
console.log("router:route() No request handler found for " + pathname);
res.writeHead(404, {"Content-Type": "text/plain"});
res.write("404 Not found");
res.end();
}
exports.route = route;
index.js
var server = require("./server");
var router = require("./router");
server.start(8080, router.route);
就我而言,处理程序位于 /TrainerCentral 子文件夹中,因此映射的工作方式如下:
localhost:8080/TrainerCentral/Recipe 将映射到 js 文件 /TrainerCentral/Recipe.js localhost:8080/TrainerCentral/Workout 将映射到 js 文件 /TrainerCentral/Workout.js
这是一个示例处理程序,它可以处理用于检索、插入、更新和删除数据的 4 个主要 HTTP 操作中的每一个。
/TrainerCentral/Workout.js
function respond(res, code, text) {
res.writeHead(code, { "Content-Type": "text/plain" });
res.write(text);
res.end();
}
module.exports = {
get: function(req, res) {
console.log("Workout:get() starting");
respond(res, 200, "{ 'id': '123945', 'name': 'Upright Rows', 'weight':'125lbs' }");
},
post: function(request, res) {
console.log("Workout:post() starting");
respond(res, 200, "inserted ok");
},
put: function(request, res) {
console.log("Workout:put() starting");
respond(res, 200, "updated ok");
},
delete: function(request, res) {
console.log("Workout:delete() starting");
respond(res, 200, "deleted ok");
}
};
使用“node index.js”从命令行启动服务器
玩得开心!