首页 > 代码库 > 用expressjs写RESTful API
用expressjs写RESTful API
expressjs
expressjs是一个基于nodejs的web开发框架:http://expressjs.com/,这篇博客目的就是用expressjs写一个关于products的最简单的RESTful API
一个最简单express的例子
package.json
{
"name": "hello-world",
"description": "hello world of express js",
"version": "0.0.1",
"private": true,
"dependencies": {
"express": "4.4.x"
}
}
安装express:
npm install
app.js
var express = require(‘express‘)
var app = express();app.get(‘/hello‘, function(req, res){
res.send(‘hello world‘)
});
var server = app.listen(3000, function() {
console.log(‘listening on port %d‘, server.address().port);
});
运行:
node app
RESTful API
GET /products
var express = require(‘express‘)
var app = express();
var products = [
{ name: ‘apple juice‘, description: ‘good‘, price: 12.12 },
{ name: ‘banana juice‘, description: ‘just so sos‘, price: 4.50 }
]
app.get(‘/products‘, function(req, res) {
res.json(products);
});
var server = app.listen(3000, function() {
console.log(‘listening on port %d‘, server.address().port);
})
GET /products/:id => 200
app.get(‘/products/:id‘, function(req, res) {
res.json(products[req.params.id]);
})
GET /products/:id => 404
app.get(‘/products/:id‘, function(req, res) {
if (products.length <= req.params.id || req.params.id < 0) {
res.statusCode = 404;
return res.send(‘Error 404: No products found‘)
}
res.json(products[req.params.id]);
})
POST /products => 201
因为我们在接受POST请求的时候,需要解析POST的body,所以,我们就要使用middleware来做这件事情,在早期版本中提供了bodyParser这样的方式。但是这种方式会创建大量的临时文件。所以,我们应该直接使用json或者urlencoded这样的middleware直接解析
在package.json中添加依赖:
"body-parser": "1.4.3"
var express = require(‘express‘),
bodyParser = require(‘body-parser‘)
var app = express()
.use(bodyParser.json());
app.post(‘/products‘, function(req, res) {
var newProduct = {
name: req.param(‘name‘),
description: req.param(‘description‘),
price: req.param(‘price‘)
}
products.push(newProduct);
res.statusCode = 201;
res.location(‘/products/‘ + products.length);
res.json(true);
});
POST /products => 400
app.post(‘/products‘, function(req, res) {
if (typeof req.param(‘name‘) === "undefined" ||
typeof req.param(‘description‘) === "undefined" ||
typeof req.param(‘price‘) === "undefined") {
res.statusCode = 400;
res.send(‘Error 400: products properties missing‘);
}
//......
});
参考资料:
http://blog.modulus.io/nodejs-and-express-create-rest-api
http://erichonorez.wordpress.com/2013/02/10/how-create-a-rest-api-with-node-js-and-express/
http://andrewkelley.me/post/do-not-use-bodyparser-with-express-js.html
http://hawkee.com/snippet/10141/
https://github.com/expressjs/body-parser