简单地来说,这是一个用于构建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.
npm install restify
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
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":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