使用 Node 创建 RESTful 应用
2015-10-22 15:42
501 查看
Node 提供了 HTTP 操作能力,并且可以使用在服务器和客户端。Node 的异步 I/O 特性保证了它具备了很强的伸缩性,所以 Node 原生就适合创建 RESTful 应用。
使用 Express
var express = require('express'); var app = express(); var router = express.Router(); // REST API router.route('/items') .get(function(req, res, next) { res.send('Get'); }) .post(function(req, res, next) { res.send('Post'); }); router.route('/items/:id') .get(function(req, res, next) { res.send('Get id: ' + req.params.id); }) .put(function(req, res, next) { res.send('Put id: ' + req.params.id); }) .delete(function(req, res, next) { res.send('Delete id: ' + req.params.id); }); app.use('/api', router); // index app.get('/', function(req, res) { res.send('Hello world'); }); var server = app.listen(3000, function() { console.log('Express is listening to http://localhost:3000'); });
使用 Koa
var koa = require('koa'); var route = require('koa-route'); var app = koa(); // REST API app.use(route.get('/api/items', function*() { this.body = 'Get'; })); app.use(route.get('/api/items/:id', function*(id) { this.body = 'Get id: ' + id; })); app.use(route.post('/api/items', function*() { this.body = 'Post'; })); app.use(route.put('/api/items/:id', function*(id) { this.body = 'Put id: ' + id; })); app.use(route.delete('/api/items/:id', function*(id) { this.body = 'Delete id: ' + id; })); // all other routes app.use(function *() { this.body = 'Hello world'; }); var server = app.listen(3000, function() { console.log('Koa is listening to http://localhost:3000'); });
使用 Hapi
var Hapi = require('hapi'); var server = new Hapi.Server(3000); server.route([ { method: 'GET', path: '/api/items', handler: function(request, reply) { reply('Get item id'); } }, { method: 'GET', path: '/api/items/{id}', handler: function(request, reply) { reply('Get item id: ' + request.params.id); } }, { method: 'POST', path: '/api/items', handler: function(request, reply) { reply('Post item'); } }, { method: 'PUT', path: '/api/items/{id}', handler: function(request, reply) { reply('Put item id: ' + request.params.id); } }, { method: 'DELETE', path: '/api/items/{id}', handler: function(request, reply) { reply('Delete item id: ' + request.params.id); } }, { method: 'GET', path: '/', handler: function(request, reply) { reply('Hello world'); } } ]); server.start(function() { console.log('Hapi is listening to http://localhost:3000'); });
相关文章推荐
- Node之remove and clean
- Node.js中的Mongoose实用笔记
- Zookeeper可视化工具。 ZK 安装 node-zk-browser。2015.10.22亲测可用
- 用node-webkit把web应用打包成桌面应用
- node express 学习2
- Node.JS 学习路线图
- 使用forever运行nodejs应用
- NodeJS概述
- Nodejs和一个简单的web页面消息推送服务
- 浅谈node.js中async异步编程
- Node学习记录
- LeetCode:Delete Node in a Linked List
- Webpack 实现 Node.js 代码热替换
- leetcode: Swap Nodes in Pairs
- LeetCode Populating Next Right Pointers in Each Node & Populating Next Right Pointers in Each Node I
- Node.js巧妙实现Web应用代码热更新
- Event Sourcing - ENode(一)
- [LeetCode] Delete Node in a Linked List
- Node.js巧妙实现Web应用代码热更新
- Webpack 实现 Node.js 代码热替换