使用 Node 创建 RESTful 应用

来源:互联网 发布:0verture for mac 编辑:程序博客网 时间:2024/05/16 09:43

Node 提供了 HTTP 操作能力,并且可以使用在服务器和客户端。Node 的异步 I/O 特性保证了它具备了很强的伸缩性,所以 Node 原生就适合创建 RESTful 应用。

使用 Express

var express = require('express');var app = express();var router = express.Router();    // REST APIrouter.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);// indexapp.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 APIapp.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 routesapp.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');});

0 0
原创粉丝点击