网站重构——轻量化的网站架构设计二,使用restify生成RESTful接口
node restify
简单地来说,这是一个用于构建REST服务的工具。
restify is a node.js module built specifically to enable you to build correct REST web services. It intentionally borrows heavily from express as that is more or less the de facto API for writing web applications on top of node.js.
安装restify
npm install restify
用restify创建rest接口
引自官网的示例var restify = require(‘restify‘); function respond(req, res, next) { res.send(‘hello ‘ + req.params.name); } var server = restify.createServer(); server.get(‘/hello/:name‘, respond); server.head(‘/hello/:name‘, respond); server.listen(8080, function() { console.log(‘%s listening at %s‘, server.name, server.url); });
运行
node app.js我们可以直接打开浏览器查看http://0.0.0.0:8080/hello/z
整合sqlite3
我们需要取出其中的数据,因为暂时找不到合理的办法,每次查询都需要打开数据库。(转载保留:网站重构)var restify = require(‘restify‘); var sqlite3 = require(‘sqlite3‘).verbose(); var db = new sqlite3.Database(‘sqlite3.db‘); var server = restify.createServer(); var content = new Array(); db.all("SELECT id,content,title,description,slug,created,updated<Plug>PeepOpenublish_date,keywords_string FROM blog_blogpost", function(err, rows) { rows.forEach(function (row) { content.push({ id:row.id, slug:row.slug, description:row.description, title:row.title, content:row.content, keywords:row.keywords_string, created:row.created, updated:row.updated, publish_date:row.publish_date }); }); function respond(req,res,next){ var data = content[req.params.name-1]; res.json(data, {‘content-type‘: ‘application/json; charset=utf-8‘}); } server.get (‘/blog/:name‘,respond); server.head (‘/blog/:name‘,respond); db.close(); }); server.listen(8080, function() { console.log(‘%s listening at %s‘, server.name, server.url); });
需要注意的是代码中的
var data = content[req.params.name-1];是因为数组的关系
res.json(data, {‘content-type‘: ‘application/json; charset=utf-8‘});这部分则是对中文的支持,也就是UTF-8
结果
打开指定ID的时候就是下面的格式。{"id":221,"slug":"restify-sqlite3-nodejs-to-refactory-website","description":"","keywords":"restify RESTful nodejs refactory","created":"2014-03-15 09:30:44.145964","updated":"2014-03-16 01:40:34.374479","publish_date":"2014-03-15 09:22:33"}
format一下
{ "content" : "", "created" : "2014-03-15 09:30:44.145964", "description" : "有趣的是在有了数据之后,我们可以用很快的速度构建出一个app,构建出一个接口。我们要做的就是将系统一部分一部分解耦出来,成为一个又一个的独立部分", "id" : 221, "keywords" : "restify RESTful nodejs refactory", "publish_date" : "2014-03-15 09:22:33", "slug" : "restify-sqlite3-nodejs-to-refactory-website", "title" : "nodejs restify sqlite3网站重构二,生成RESTful接口", "updated" : "2014-03-16 01:40:34.374479" }运行
forever start app.js
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。