express 实现restful风格代码

直接上代码:

//app.js


var app = express();

// all environments

app.set('port', process.env.PORT || 3000);

app.set('views',path.join(__dirname,'views'));

app.use(bodyParser.json());

app.use(express.static(path.join(__dirname, 'public')));

app.get('/users', user.list);

app.get('/users/:id', user.get);

app.delete('/users/:id', user.delete);

app.post('/users', user.add);

app.put('/users/:id', user.update);

http.createServer(app).listen(app.get('port'), function(){

console.log('Express server listening on port ' + app.get('port'));

});

//user.js


var users = require('./users').users;

exports.list = function(req, res){

res.setHeader('Content-Type', 'application/json;charset=utf-8');

res.send(users);

};

exports.get = function(req, res){

res.setHeader('Content-Type', 'application/json;charset=utf-8');

res.send(users[req.param('id')]);

};

exports.delete = function(req, res){

res.setHeader('Content-Type', 'application/json;charset=utf-8');

delete users[req.param('id')];

res.send({status:"success", message:"delete user success"});

console.log(users);

};

exports.update = function(req, res){

res.setHeader('Content-Type', 'application/json;charset=utf-8');

users[req.body.id] = req.body;

res.send({status:"success", message:"update user success"});

console.log(users);

};

exports.add = function(req, res){

res.setHeader('Content-Type', 'application/json;charset=utf-8');

console.log(req.body);

users[req.body.id] = req.body;

res.send({status:"success", message:"add user success"});

console.log(users);

};

//users.js


exports.users = {

"1":{

id:1,

name:"user1",

password:"password1"

},

"2":{

id:2,

name:"user2",

password:"password2"

},

"3":{

id:3,

name:"user3",

password:"password3"

}

}

你可能感兴趣的:(express 实现restful风格代码)