Server API
原文:http://mcavage.me/node-restify/#server-api
最准系统响应服务器:
var restify = require('restify');
function respond(req, res, next) {
res.send('hello ' + req.params.name);
next();
}
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);
});
试着打用下面的 curl 命令来感受RESTify将会把它转换成什么:
$ curl -is http://localhost:8080/hello/mark -H 'accept: text/plain'
HTTP/1.1 200 OK
Content-Type: text/plain
Content-Length: 10
Date: Mon, 31 Dec 2012 01:32:44 GMT
Connection: keep-alive
hello mark
$ curl -is http://localhost:8080/hello/mark
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 12
Date: Mon, 31 Dec 2012 01:33:33 GMT
Connection: keep-alive
"hello mark"
$ curl -is http://localhost:8080/hello/mark -X HEAD -H 'connection: close'
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 12
Date: Mon, 31 Dec 2012 01:42:07 GMT
Connection: close
请注意,在默认情况下,curl 使用 Connection:keep-alive。为了使头部的方法立即返回,你就需要通过 Connection:close。
由于curl 通常与REST API一起使用,RESTify提供一个插件来解决围绕这个特质的 curl。该插件检查是否用户代理是curl。如果是,它设置连接头为“close”,并删除“的Content-Length”头。
server.pre(restify.pre.userAgentConnection());
看 pre 方法,以获取更多信息。
创建一个服务
创建服务器很简单,你只需调用createServer API,它带有一个对象选项,下面列出的选项(并且 listen() 采用相同的参数作为node 的 http.Server.listen):
var restify = require('restify');
var server = restify.createServer({
certificate: ...,
key: ...,
name: 'MyApp',
});
server.listen(8080);
选项 | 类型 | 描述 |
---|---|---|
certificate | String | 如果你想创建一个HTTPS服务器,通过PEM编码的证书和密钥 |
key | Stirng | 如果你想创建一个HTTPS服务器,通过PEM编码的证书和密钥 |
formatters | Object | 用户响应格式化程序res.send() |
log | Object | 您可以选择通过用 bunyan 实例;不是必需 |
name | String | 默认情况下,这将设置服务器响应头,默认为的RESTify |
spdy | Object | 被node-spdy接受的任何选项 |
version | String | 默认版本为所有的路由设置 |
handleUpgrades | Boolean | 顶升级事件来自node HTTP服务器,推送连接:升级请求,通过定期请求处理链;默认为false |
httpServerOptions | Object | 通过node-HTTPS服务器接受的任何选项。如果提供了以下的RESTify服务器选项将被忽略:spdy,ca,certificate,key,passphrase,rejectUnauthorized,requestCert和ciphers; 然而所有这些可以在httpsServerOptions被指定。 |