有趣的是在有了数据之后,我们可以用很快的速度构建出一个app,构建出一个接口。我们要做的就是将系统一部分一部分解耦出来,成为一个又一个的独立部分
简单地来说,这是一个用于构建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,updatedPeepOpenublish_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: 213,
slug: "be-a-geek-chapter-7-anywhere-css-2",
description: "样式与目标 下面也就是我们的样式",
title: "be a geek 7:无处不在的css 2",
content: "",
keywords: "beageek begeek javascript anywhere anywherecss",
created: "2014-03-07 01:00:51.901267",
updated: "2014-03-07 01:00:55.198979",
publish_date: "2014-03-07 01:00:51.269542"
}
运行
forever start app.js
围观我的Github Idea墙, 也许,你会遇到心仪的项目