您的位置:首页 > Web前端 > Node.js

使用 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'); });
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: