restful用法

http://www.cnblogs.com/wen-wen/p/6149847.html
一.创建services文件夹
services文件夹下
1.BaseService.js
class Service{
constructor(){
console.log('service的constructor');
}
add(obj, name,callback){
console.log('service的add');
}
delete(){
console.log('service的delete');
}
}
exports.service = Service;

2.UserService.js

var BaseService = require('./BaseService').service;

class UserService extends BaseService{
constructor(){
super();
}
add(obj, name,callback){
console.log(obj);
console.log(name);
console.log(callback);
console.log('UserService的add');
callback({say:'收到'});
}
delete(){
console.log('UserService的delete');
}
}
exports.service = UserService;

3.services.js
exports.userService = require('./UserService').service;

二:router路由中创建api.js
var express = require('express');
var router = express.Router();
var Services = require('../services/services');

router.get('/restful',function(req,res,next){
res.render('restful');
})

router.get('/:name?/:method?/:par?',function(req,res,next){
var name = req.params.name || 'empty';
var method = req.params.method || 'empty';
var par = req.params.par || '';

console.log(name+'Service');
var service = new Services[name+'Service']();
var obj = req.query || {};
obj.par = par;

if(!Services[name+'Service']){
service = new Services.emptyService();
}
service[method](obj,name,function(result){
//res.json(result);
res.json({id:1,name:'张三'});
});
return;
});

 

module.exports = router;

三:views/restful.ejs中
<html>
<head>
<script src="/javascripts/jquery-2.1.4.min.js"></script>
<script>
function dian(){
$.get('/api/user/add',function(res){
alert(res.name);
});
}
</script>
</head>
<body>
<input type='button' value='点' onclick='dian()'/>
</body>
</html>

posted @ 2017-08-30 17:22  开始战斗  阅读(483)  评论(0编辑  收藏  举报