用express寫個簡單的CRUD

方健發表於2015-06-28

作者:方健(轉載請註明出處)
程式碼: https://bitbucket.org/fangj/example-simple-restful

npm install express-generator -g
express myapp
cd myapp
npm install
npm install lodash --save
npm start

vi app.js

var tasks=require('./routes/tasks');
app.use('/tasks', tasks);

vi routes/tasks.js

'use strict';
var express = require('express');
var router = express.Router();
var _=require('lodash');

var tasks=[{id:'1',name:'hello'},{id:'2',name:'world'}]; //simple data 
var id=3;

//return all
router.get('/', function(req, res) {
    res.json(tasks);
});

//create new
router.post('/', function(req, res) {
    var newTask=req.body;
    newTask.id=''+(id++);
    tasks.push(newTask);
    res.json(newTask);
});

//get one
router.get('/:id', function(req, res) {
    var task=_.find(tasks,{id:req.params.id});
    res.json(task);
});

//update one
router.put('/:id', function(req, res) {
    _.remove(tasks,{id:req.params.id});
    var newTask=req.body;
    newTask.id=req.params.id;
    tasks.push(newTask);
    res.json(newTask);
});

//remove one
router.delete('/:id', function(req, res) {
    _.remove(tasks,{id:req.params.id});
    res.json({id:req.params.id});
});

module.exports = router;

客戶端:

cd public
bower install restful.js
vi public/test.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test</title>
    <script type="text/javascript" src="bower_components/restful.js/dist/restful.min.js"></script>
</head>
<body>

<script type="text/javascript">
var api = restful('localhost').port(3000);
var tasksCollection = api.all('tasks');

tasksCollection.getAll().then(function(response) {
    tasks=response.body();
    tasks.forEach(function  (task) {
        console.log(task.data());
    });
});

var tasks1 = api.one('tasks',1);
tasks1.get().then(function(response) {
    console.log('tasks1',  response.body().data())
});

tasknew=tasksCollection.post({"form":"client"});
tasknew.then(function  (newT) {
    console.log(newT.data());
})

tasksCollection.put(4,{"put":"put"});

tasksCollection.get(4).then(function  (newT) {
    console.log(newT.data());
})

</script>

</body>
</html>

相關文章